Inner intervals are always inside the global one.
All intervals are integer, left-closed, right-open intervals.
Let’s take this example.
The "global" interval is [0, 22[.
"Inner" intervals are [3, 6[ and [12, 15[.
For this example I expect :
[0, 3[ U [3, 6[ U [6, 12[ U [12, 15[ U [15, 22[
I’ve tried to define a function but then messed up with indices while iterating over intervals.
def allspans(r, spans):
pass
allspans((0, 22), [(3,6), (12,15)]) # expected : [(0, 3), (3, 6), (6, 12), (12, 15), (15, 22)]
>Solution :
Yes you have to iterate over your spans but take care of maintaining a position to correctly fill the spaces between.
from typing import Generator
def allspans(r, spans) -> Generator:
pos = 0
for lower, upper in spans:
if pos < lower:
yield pos, lower
yield lower, upper
pos = upper
if pos <= r[1]:
yield pos, r[1]
I find it easier to use a Generator.
Just use list() to convert to a List.
list(allspans((0, 22), [(3,6), (12,15)])) # [(0, 3), (3, 6), (6, 12), (12, 15), (15, 22)]