我需要一些编码方面的帮助。
给出hh:mm格式的时钟时间值序列,找出任意两个时间值之间以分钟为单位的最小差异。
例如,考虑以下值序列:
input = ['01:00','01:25'],最小差= 25分钟
input = ['11:00','12:02','11:58'],最小差= 4分钟
输入= ['22:00','00:30'],最小差= 150分钟
在情况1中,给定输入序列中的两个值,最小的差异是两个时钟时间值之间的分钟数,即25分钟。
在情况2中,给定输入中的三个值,最小的差异是值“ 11:58”和“ 12:02”之间的分钟数。
在情况3中,需要考虑有两种方法可以沿顺时针和逆时针方向计算两个时间值之间的差。顺时针方向相差150分钟,逆时针方向相差1290分钟。由于问题陈述是关于找到最小的差异,因此在计算差异时应考虑较小的值。
您的任务是实现minimum_minute_difference函数的详细信息,以确定所提供的输入值列表中任意两个值之间的最小差。预期该算法将以分钟为度量单位,返回一个表示最小差异的数字。在上述情况下,该函数应分别返回25、4和150。期望该差为正数,即,将其视为绝对值。如果输入中存在两个相似的时间值,则差可以为零。
我编写的代码:
import time
from datetime import datetime
def minimum_time_difference(timeInstants):
timeInstants=sorted((time.strptime(d, "%H:%M") for d in timeInstants))
fmt = '%H:%M'
timeInstants=sorted(timeInstants)
diff = '24:59' #I need to assign a very big value here
diff = datetime.strptime(diff, fmt)
n=len(timeInstants)
for i in range(n):
timeInstants[i] = datetime.strptime(timeInstants[i], fmt)
for i in range(n):
print(timeInstants[i])
if timeInstants[i+1] - timeInstants[i] < diff:
diff = timeInstants[i+1] - timeInstants[i]
print(diff)
return diff
def main():
timeInstants = ['11:00','12:02','11:58']
minimum_value = minimum_time_difference(timeInstants)
message = 'Given time instant values {0}, minimum difference between any two time instants is {1}\n'.format(
timeInstants, minimum_value)
print(message)
if __name__ == '__main__':
main()
我编写的代码给我错误:
TypeError: unorderable types: datetime.timedelta() < datetime.datetime
我在做什么错,我的方法正确吗?
答案 0 :(得分:2)
您可以自己创建所有时间的itertools.product(每次组合在一起,包括自身在内)。然后计算这些时间对之间的差异,并取大于0的最小值(因为自我-自我配对)。这样,您只可以比较timedelta(或者您只是获得最小timedelta),而无需将时间与timedelta进行比较。
import datetime
from datetime import datetime, timedelta
from itertools import product
def minimum_time_difference(timeInstants):
# same time twice in list: set is shorter then list: return 0
if len(timeInstants) != len(set(timeInstants)):
return 0
# convert to datetime
timeInstants = set(datetime.strptime(d, "%H:%M") for d in timeInstants)
# convert to timedeltas from pairs
diffs = set(abs(a-b ) for a,b in product(timeInstants, timeInstants))
diffs |= set(abs(a-(b+timedelta(days=1))) for a,b in product(
timeInstants, timeInstants))
print(diffs)
# remove 0 times
m = min(d for d in diffs if d)
return m
times = [ '00:00','23:59']
minimum_value = minimum_time_difference(times)
print(minimum_value)
输出:
{datetime.timedelta(0), datetime.timedelta(1, 86340), datetime.timedelta(0, 60),
datetime.timedelta(1), datetime.timedelta(0, 86340)}
0:01:00 # 1 minutes