首页 > 代码库 > 【leetcode?python】Binary Watch

【leetcode?python】Binary Watch

#-*- coding: UTF-8 -*-
from itertools import combinations


class Solution(object):
    
    hourList=[8,4,2,1]
    minList=[32,16,8,4,2,1]
    
    
    def selectHour(self,hourNum):
        if hourNum==0:
            return [0]
        #迭代工具模块包含了操做指定的函数用于操作迭代器
        selectHourList=[]
        hourCombin=list(combinations(self.hourList, hourNum))
        for combine in hourCombin:
            sumT=sum(combine)
            if(sumT<=12):
                selectHourList.append(sumT)

        return selectHourList
    
    def selectMinute(self,minNum):
        if minNum==0:return [0]
        #迭代工具模块包含了操做指定的函数用于操作迭代器
        selectMinList=[]
        
        minCombin=list(combinations(self.minList, minNum))
        for combine in minCombin:
            sumT=sum(combine)
            if(sumT<=59):
                selectMinList.append(sumT)

        return selectMinList
    
    def combinHourMin(self,hourList,minList):

        #直接使用for循环就可以了
        resultsList=[]
        for hour in hourList:
            for min in minList:
 
                minStr=str(min) if len(str(min))>1 else (‘0‘+str(min))
 
                strTmp=str(hour)+‘:‘+minStr
 
                resultsList.append(strTmp)
     
        return resultsList
    def handleResult(self,resultsList):
        reList=[]
        for item in resultsList:
            for i in item:
                reList.append(i)
        return reList
    
    def readBinaryWatch(self, num):
        if(num>8):
            return
#        elif(num<=0):
#            return ‘0:00‘
        maxHours=3 if num>=3 else num
        maxMinutes=5
        hourLeastNum=0 if (num-maxMinutes)<=0 else (num-maxMinutes)
        
        resultsList=[]

        for hourNum in range(hourLeastNum,maxHours+1):

            selectHourList=self.selectHour(hourNum)
            selectMinList=self.selectMinute(num-hourNum)
            resultsList.append(self.combinHourMin(selectHourList,selectMinList))

        return self.handleResult(resultsList)
    
sol=Solution()
print sol.readBinaryWatch(num=0)
print len(sol.readBinaryWatch(num=0))
         

【leetcode?python】Binary Watch