Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have an interval of integers that comprises some inner intervals. Given these intervals I want to compute a list including the intervals between

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[

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading