Python: divmod的神奇作用

今天在解一道codewars的题目的时候,被divmod的作用吸引到了。
题目是这样的:

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 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (99:59:59)

You can find some examples in the test fixtures:

Test.assert_equals(make_readable(0), "00:00:00")
Test.assert_equals(make_readable(5), "00:00:05")
Test.assert_equals(make_readable(60), "00:01:00")
Test.assert_equals(make_readable(86399), "23:59:59")
Test.assert_equals(make_readable(359999), "99:59:59")

就是按照输入的秒数,按照要求返回字符串。
我一开始陷入了错误的思路,想按范围判断,10秒以下的怎么输出,10秒以上的怎么输出,分钟和小时类似。要写一大堆的elif。
实际上,只要使用02d就可以解决:

02d formats an integer (d) to a field of minimum width 2 (2), 
with zero-padding on the left (leading 0):

稍微易于理解的解法:

def make_readable(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    res = '%02d:%02d:%02d' %(hours, minutes, seconds)
    return res

在提交之后,发现更简洁的解法:

def make_readable_best(s):    
    return '{:02}:{:02}:{:02}'.format(s / 3600, s / 60 % 60, s % 60)

真是受教颇深!

你可能感兴趣的:(Python: divmod的神奇作用)