简化功能

时间:2013-01-27 18:11:48

标签: python string int slice typeconverter

我写了这个函数,我认为它会起作用,但我不是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

1 个答案:

答案 0 :(得分:5)

我会使用HH:MMm = int(HH) * 60 + int(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'