How to find the intersection of list of intervals?

Viewed 101

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?

2 Answers

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 

I won't solve the problem for you, however idea is simple:

Take first element of your list as a result. Then iterate from the second position in the list till the end and reassign your result to intersection of result and current element.

what you have at the end is your intersection

Related