divmod在python中是什么意思_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)

真是受教颇深!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值