Search code examples
pythonsetrangeintersectioninfinity

Compare open ranges in python for intersection


I compare ranges as follows:

def get_intersections(ranges):
    """Marks ranges if they intersect with other ranges with True.
    """
    intersection_idxs = len(ranges) * [False]
    for idx in range(len(ranges)):
        r, rest = set(ranges[idx]), [set(_) for _ in ranges[:idx] + ranges[idx+1:]]
        # Uncomment to understand.
        # print(r)
        # print(rest)
        if any([len(set.intersection(r, r2)) > 0 for r2 in rest]):
            intersection_idxs[idx] = True
    return intersection_idxs

# Example 1.
ran1 = range(4,9)
ran2 = range(2,5)
ran3 = range(2,3)
ranges = [ran1, ran2, ran3]
print(get_intersections(ranges))

# Example 2.
ran1 = range(1,5)
ran2 = range(2,5)
ran3 = range(7,9)
ranges = [ran1, ran2, ran3]
print(get_intersections(ranges))

# Example 3.
#ran1 = range(1,inf)
#ran2 = range(2,5)
#ran3 = range(7,9)
#ranges = [ran1, ran2, ran3]
#print(get_intersections(ranges))
#>> [True, True, True]

As you can see, the first 2 examples work quite well. Since all ranges intersect in the first example, the get_intersections function returns [True, True, True].

In the second example, the last range (range(7,9)) does not intersect with other ranges. Therefore [True, True, False] is returned.

I'd like to realize example 3 (see pseudocode). In this case, the first range goes from 1 to infinity which means that it intersects with the other ranges. The other ranges therefore automatically intersect as well. Right now I see no way how to do this. Is there any way to use open ranges or ranges to infinity in a similar way?


Solution

  • I don't know why you use range.

    You could use tuples with lower and upper bound (a,b).

    When you need inf you can use math.inf which is greater than any real number.

    So (a,b) interesect with (c,d) if c<b and a<d.