2

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

1 回答 1

5

我会HH:MM使用m = 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'
于 2013-01-27T18:15:54.137 回答