An algorithm for finding n interval ranges and Union sets by python

there are n ordered sets, and each element of the set is a range. Find the intersection of n sets, for example, the union of sets {[2jue 4], [9jue 13]} and {[6jue 12]} is {[2jue 4], [6jue 13]}. How to implement

with python?
Feb.27,2021

python has an interval processing library interval

from interval import Interval, IntervalSet

data = [(2, 4), (9, 13), (6, 12)]

intervals = IntervalSet([Interval.between(min, max) for min, max in data])
print [(_.lower_bound, _.upper_bound) for _ in intervals]

sort in the first step and traverse in the second step.


: N

-sharp -*- coding: utf-8 -*-
from functools import reduce


def intersection(range_a, range_b):
    """ None """
    if not (range_a and range_b):
        return None
    lower_a, upper_a = range_a
    lower_b, upper_b = range_b
    if lower_b < lower_a:
        if upper_b < lower_a:
            return None
        if upper_b < upper_a:
            return (lower_a, upper_b)
        return tuple(range_a)
    if lower_b < upper_a:
        if upper_b < upper_a:
            return tuple(range_b)
        return (lower_b, upper_a)
    return None


def intersectionN(ranges):
    """  N None """
    return reduce(intersection, ranges)


def _test_intersection_algorithm(f):
    """
     f

    -sharp 
      * i:  
      * i+1: 

    -sharp 
       (3,6)  (x,y) :
      1. x < 3,     y < 3
      2. x < 3, 3 < y < 6
      3. x < 3, 6 < y

      4. 3 < x < 6,     y < 6
      5. 3 < x < 6, 6 < y

      6. 6 < x, 6 < y
    """
    test_records = [
        [(3, 6), (1, 2)],   None,
        [(3, 6), (1, 4)],   (3, 4),
        [(3, 6), (1, 7)],   (3, 6),

        [(3, 6), (4, 5)],   (4, 5),
        [(3, 6), (4, 7)],   (4, 6),

        [(3, 6), (7, 9)],   None,
    ]

    for i in range(len(test_records)/2):
        input_set = test_records[2*i]
        expected = test_records[2*i+1]
        assert f(input_set) == expected, (
            'input: %s, expected: %s' % (input_set, expected))


def test_intersection():
    -sharp  pytest 
    _test_intersection_algorithm(intersectionN)

and so on, you can implement the union algorithm.

Menu