Search code examples
pythonintersection

How to find the intersection of list of intervals?


I have list of intervals like this:

[[-5, 10], [-3, 5], [-53.7228, 3.72281], [-3, 4], [-6.32456, 6.32456]]

and i need to find intersection of all these intervals

answer is

[-3,3.72281]

Maybe someone knows how to do it?


Solution

  • For this trivial example, you seem to want the maximum of the first value and minimum of the second value.

    l = [[-5, 10], [-3, 5], [-53.7228, 3.72281], [-3, 4], [-6.32456, 6.32456]]
    
    v1 = max([pair[0] for pair in l])  # -3
    v2 = min([pair[1] for pair in l])  # 3.72281
    
    assert v1 < v2