Another itertools solution


  • 0

    Let itertools.combinations produce the bit sets with the right size, then compute hour and minute from it and add the time to the output if it's valid.

    def readBinaryWatch(self, num):
        times = []
        for bits in itertools.combinations(range(10), num):
            h = m = 0
            for b in bits:
                if b < 6:
                    m += 2**b
                else:
                    h += 2**(b-6)
            if h < 12 and m < 60:
                times.append('%d:%02d' % (h, m))
        return times
    

    Just a variation:

    def readBinaryWatch(self, num):
        times = []
        for bits in itertools.combinations(range(10), num):
            m = sum(2**b for b in bits if b < 6)
            h = sum(2**(b-6) for b in bits if b > 5)
            if h < 12 and m < 60:
                times.append('%d:%02d' % (h, m))
        return times

Log in to reply
 

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