查找日期是否在N对列表中重叠 [英] Find if dates are overlapping in a list of N pairs
本文介绍了查找日期是否在N对列表中重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出开始时间和开始时间的列表,我想查找列表中是否包含重叠的条目:
Given list of start times and begin times, I would like to find if the list contains overlapping entries:
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')]
我从这个非常类似的问题中借用了一些代码,以测试测试重叠的日期对:
I borrowed some code from this very similar question to test overlapping pair of dates:
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
我用来测试条目列表的功能:
My function to test the list of entries:
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
使用时,其工作方式如下:
When used, it works like this:
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]
但是:
- 如果这对于大型列表非常有效,我仍在辩论.
- 我想知道是否有人可以提供更好的解决方案?
推荐答案
我提出了测试重叠的方法,即查找日期的所有交集的方法:
I propose that way to testing the overlap, a way to find all intersections of a date :
def test_overlap(dt1_st, dt1_end, dt2_st, dt2_end):
return not (dt1_st < dt2_end and dt1_end >dt2_st)
这涵盖了重叠的所有可能性
That's cover the all possibilities of overlapping
这篇关于查找日期是否在N对列表中重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文