pythonrangeoverlap

Subtract Overlaps Between Two Ranges Without Sets


NO SETS!

I can't use Sets because:


Using only the endpoints of the of the ranges, is there an optimal way to subtract two lists of ranges?

Example:

r1 = (1, 1000), (1100, 1200)  
r2 = (30, 50), (60, 200), (1150, 1300)

r1 - r2 = (1, 29), (51, 59), (201, 1000), (1100, 1149)

Other info:

Thanks.


Solution

  • The interval package may provide all that you need.

    from interval import Interval, IntervalSet
    r1 = IntervalSet([Interval(1, 1000), Interval(1100, 1200)])
    r2 = IntervalSet([Interval(30, 50), Interval(60, 200), Interval(1150, 1300)])
    print(r1 - r2)
    
    >>> [1..30),(50..60),(200..1000],[1100..1150)