Distinct time slots from multiple intersecting intervals

482 views Asked by At

I have the following time slots within a single day:

1) 9:00 to 13:00

2) 9:30 to 10:30

3) 9:30 to 10:30 (this interval is intentionally here 2x)

4) 11:00 to 12:00

I can visualize the time slots on a horizontal time line:

Timeslot 1)

 |--------------------------------------------|

 9:00                                       13:00

Timeslot 2)

      |-------------|

      9:30      10:30

Timeslot 3)

      |-------------|

      9:30      10:30

Timeslot 4)

                           |-------------|

                           11:00      12:00

I am trying to figure out a Python method which will take N number of time slots on input and return distinct time windows plus how many times a window overlaps another one. For the above example, the expected output should look like this:

Window 1: 9:00 - 9:30, slots count 1

Window 2: 9:30 - 10:30, slots count 3

Window 3: 10:30 - 11:00, slots count 1

Window 4: 11:00 - 12:00, slots count 2

Window 5: 12:00 - 13:00, slots count 1

Could anyone please point me into the right direction on how to solve this in Python 3?

1

There are 1 answers

0
Bill Bell On

Use the facilities in sympy sets: intervals to make manipulating the intervals more convenient. That's the first part.

Perform the calculation recursively. Start with any one of the given intervals, begin with it as the 'first intersection' and go 'down' one step. Select another interval and calculate the intersection of the preceding intersection with it. If this intersection is non-empty go 'down' another step. Otherwise, return to the top with this intersection as the value of the intersections of the intervals considered. Likewise, if the intersection passed is empty go 'up' and return from there. Start from each of the given intervals.