Skip to content Skip to sidebar Skip to footer

Find If Dates Are Overlapping In A List Of N Pairs

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')] wro

Solution 1:

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


Solution 2:

This is similar to interval overlapping problem. Elaborating on pkacprzak's post.

Sort a list of events by time. Keep another list of active elements.

Process linearly as so..

For each event/element..

  1. add to active elements list if start point.
  2. remove from active elements list if end point.
  3. Additionally, at each start point, the present active elements are overlapping with the current element.

Also, look at other such solutions for interval overlaps.like this one. how to overlap intervals efficiently


Solution 3:

If no two pairs start at the same time, you could treat the time stamps as numeric values in "minutes since midnight", then sort the input list by the start time and then check whether the end time of any element is greater than the start time of the next element:

from operator import itemgetter
from itertools import izip

def asNumber(s):
    colon = s.find(':')
    return int(s[:colon]) * 60 + int(s[colon+1:])

def isValid(l):
  numericPairs = [(asNumber(a), asNumber(b)) for (a,b) in l]
  sortedPairs = sorted(numericPairs, key=itemgetter(0))
  return all(startB >= endA for ((startA, endA), (startB, endB)) in izip(sortedPairs, sortedPairs[1:]))

Post a Comment for "Find If Dates Are Overlapping In A List Of N Pairs"