Union of multiple ranges

后端 未结 5 606
悲&欢浪女
悲&欢浪女 2020-11-27 07:28

I have these ranges:

7,10
11,13
11,15
14,20
23,39

I need to perform a union of the overlapping ranges to give ranges that are not overlappi

5条回答
  •  春和景丽
    2020-11-27 07:56

    Old question. But I wanted to add this answer for future references. sympy can be used to achieve union of intervals:

    from sympy import Interval, Union
    def union(data):
        """ Union of a list of intervals e.g. [(1,2),(3,4)] """
        intervals = [Interval(begin, end) for (begin, end) in data]
        u = Union(*intervals)
        return [list(u.args[:2])] if isinstance(u, Interval) \
           else list(u.args)
    

    If output of Union is more than two intervals is a Union object while when there is a single interval, the output is an Interval object. That's the reason for the if statement in the return line.

    examples:

    In [26]: union([(10, 12), (14, 16), (15, 22)])
    Out[26]: [[10, 12], [14, 22]]
    
    In [27]: union([(10, 12), (9, 16)])
    Out[27]: [[9, 16]]
    

提交回复
热议问题