Union of multiple ranges

后端 未结 5 617
悲&欢浪女
悲&欢浪女 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:52

    The following function works well for the given example data:

    def range_overlap_adjust(list_ranges):
        overlap_corrected = []
        for start, stop in sorted(list_ranges):
            if overlap_corrected and start-1 <= overlap_corrected[-1][1] and stop >= overlap_corrected[-1][1]:
                overlap_corrected[-1] = min(overlap_corrected[-1][0], start), stop
            elif overlap_corrected and start <= overlap_corrected[-1][1] and stop <= overlap_corrected[-1][1]:
                break
            else:
                overlap_corrected.append((start, stop))
        return overlap_corrected
    

    Usage

    list_ranges = [(7, 10), (11, 13), (11, 15), (14, 20), (23, 39)]   
    print(range_overlap_adjust(list_ranges))
    # prints [(7, 20), (23, 39)]
    

提交回复
热议问题