Python AC soutien using itertools


  • 1
    K
    import itertools
    class Solution(object):
        def convert(self,l): # print the result
            res = []
            for pair in l:
                h , m = pair[0] , pair[1]
                for i in h:
                    for j in m:
                        t = i + ':'
                        t = t + '0' + j if len(j) == 1 else t + j
                        res += [t]
                        t = ''
            return res
        def readBinaryWatch(self, num):
            """
            :type num: int
            :rtype: List[str]
            """
            hour , minute , tem = [1,2,4,8] , [1,2,4,8,16,32] ,[ ]
            
            for i in range(num + 1):
                m = num - i
                if i > 0:
                    combination1 = itertools.combinations(hour, i) # all possible hour
                    hh = set()
                    for i in combination1:
                        if sum(i) < 12: # just keep vaild hour
                            hh.add(str(sum(i))) 
                else:
                    hh = set('0')
                
                if m > 0:
                    combination2 = itertools.combinations(minute, m) # all possible minute
                    mm = set()
                    for i in combination2:
                        if sum(i) < 60: # just keep  vaild minute
                            mm.add(str(sum(i))) 
                else:
                    mm = set('00')
                
                tem.append([hh,mm])
            return self.convert(tem)

  • 3
    C

    Same idea. But simpler.

    hours = [8, 4, 2, 1]
    minutes = [32, 16, 8, 4, 2, 1]
    
    
    class Solution(object):
        def readBinaryWatch(self, num):
            """
            :type num: int
            :rtype: List[str]
            """
            ans = []
            for i in range(0, num+1):
                for _h in self.get_time(hours, i, 12):
                    for _m in self.get_time(minutes, num-i, 60):
                        ans.append('{:}:{:02}'.format(_h, _m))
            return ans
    
        def get_time(self, time, n, limit):
            ans = []
            for comb in itertools.combinations(time, n):
                tmp = sum(comb)
                if tmp < limit:
                    ans.append(tmp)
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.