gpt4 book ai didi

python - 简化功能

转载 作者:行者123 更新时间:2023-11-28 22:00:36 25 4
gpt4 key购买 nike

我已经编写了这个函数,我认为它可以工作,但我不是 100% 确定。但我很好奇这很复杂。有什么方法可以使它更简单吗?

这三个参数是 'HH:MM' 形式的时间,其中 00 <= HH <= 23 和 00 <= MM <= 59。前两个时间是时间估计,第三个是实际时间。返回最接近实际时间的时间估计,前两个参数之一。如果它们同样接近,则第一次返回。

(str, str, str) -> str  


def closest_time(guess1, guess2, answer):
if abs((int(answer[:2])) - (int(guess1[:2])) > ((int(answer[:2])) - int(guess2[:2]))):
return guess2
if abs((int(answer[:2])) - (int(guess1[:2])) < ((int(answer[:2])) - int(guess2[:2]))):
return guess1
if abs((int(answer[:2])) - (int(guess1[:2])) == ((int(answer[:2])) - int(guess2[:2]))):
if abs((int(answer[3:])) - (int(guess1[3:])) > ((int(answer[3:])) - int(guess2[3:]))):
return guess2
if abs((int(answer[3:])) - (int(guess1[3:])) < ((int(answer[3:])) - int(guess2[3:]))):
return guess1
if abs((int(answer[3:])) - (int(guess1[3:])) == ((int(answer[3:])) - int(guess2[3:]))):
return guess1

最佳答案

我会使用 m = int(HH) * 60 + int(MM)HH:MM 格式转换为分钟。这应该可以大大简化问题。

综合起来:

>>> def to_minutes(s):
return int(s[:2]) * 60 + int(s[-2:])

>>> def closest_time(guess1, guess2, answer):
g1, g2, a = map(to_minutes, [guess1, guess2, answer])
return guess1 if abs(g1 - a) <= abs(g2 - a) else guess2

>>> closest_time('08:05', '10:30', '08:10')
'08:05'
>>> closest_time('08:05', '10:30', '10:05')
'10:30'

关于python - 简化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14550466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com