Human Readable Time(codewar)
题目:Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS
)
HH
= hours, padded to 2 digits, range: 00 - 99MM
= minutes, padded to 2 digits, range: 00 - 59SS
= seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (99:59:59
)
我的答案:592ms
def make_readable(seconds): hour = seconds // (60*60) seconds = seconds % (60*60) mm = seconds // 60 seconds = seconds % 60 return ('{:0>2d}:{:0>2d}:{:0>2d}'.format(hour, mm, seconds))
正常的思路,分别求出hour,mm,seconds,然后使用format格式表达
答案二:
def make_readable(seconds): hours, seconds = divmod(seconds, 60 ** 2) minutes, seconds = divmod(seconds, 60) return '{:02}:{:02}:{:02}'.format(hours, minutes, seconds)
使用divmod,同时取余和取模,不需要对seconds多次单独赋值,简单明了
答案三:
def make_readable(s): return '{:02}:{:02}:{:02}'.format(s / 3600, s / 60 % 60, s % 60)