给定开始时间和开始时间列表,我想知道列表是否包含重叠条目:
timesok = [('9:30', '10:00'), ('10:00', '10:30'), ('10:30', '11:00')]
wrongtimes1 = [('9:30', '10:00'), ('9:00', '10:30'), ('10:30', '11:00')]
wrongtimes2=[('9:30', '10:00'), ('10:00', '10:30'), ('9:15', '9:45')]
我从这个非常相似的问题中借用了一些代码来测试重叠的日期对:
def test_overlap(dt1_st, dt1_end, dt2_st, dt2_end):
r1 = Range(start=dt1_st, end=dt1_end)
r2 = Range(start=dt2_st, end=dt2_end)
latest_start = max(r1.start, r2.start)
earliest_end = min(r1.end, r2.end)
overlap = (earliest_end - latest_start)
return overlap.seconds
我测试条目列表的功能:
def find_overlaps(times):
pairs = list(combinations(times, 2))
print pairs
for pair in pairs:
start1 = dt.strptime(pair[0][0], '%H:%M')
end1 = dt.strptime(pair[0][1], '%H:%M')
start2 = dt.strptime(pair[1][0], '%H:%M')
end2 = dt.strptime(pair[1][1], '%H:%M')
yield test_overlap(start1, end1, start2, end2) > 0
使用时,它的工作原理如下:
In [257]: list(find_overlaps(timesok))
[(('9:30', '10:00'), ('10:00', '10:30')), (('9:30', '10:00'), ('10:30', '11:00')), (('10:00', '10:30'), ('10:30', '11:00'))]
Out[257]: [False, False, False]
In [258]: list(find_overlaps(wrongtimes1))
[(('9:30', '10:00'), ('9:00', '10:30')), (('9:30', '10:00'), ('10:30', '11:00')), (('9:00', '10:30'), ('10:30', '11:00'))]
Out[258]: [True, False, False]
In [261]: list(find_overlaps(wrongtimes2))
[(('9:30', '10:00'), ('10:00', '10:30')), (('9:30', '10:00'), ('9:15', '9:45')), (('10:00', '10:30'), ('9:15', '9:45'))]
Out[261]: [False, True, False]
然而:
- 如果这对大型列表非常有效,我仍在争论自己。
- 我想知道是否有人可以提供更好的解决方案?