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]
However:
- I am still debating myself if this is very efficient to large lists.
- I was wondering if someone can offer a better solution?