Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Determine overlaps of 3 ranges

I had a question regarding how I should go about determining overlaps of three ranges in Python without using any existing libraries :

For instance if I have three ranges as (10,20)(15,25)(18,30), how should I go about finding overlaps between them ?

My answer should be (18,19,20)

Any help would be much appreciated. Thanks !

like image 973
user1418321 Avatar asked Dec 15 '22 23:12

user1418321


2 Answers

The overlap goes from the highest start point to the lowest end point:

ranges = [(10,20), (15,25), (18,30)]
starts, ends = zip(*ranges)
result = range(max(starts), min(ends) + 1)

Test:

>>> print(*result)
18 19 20
like image 84
Reinstate Monica Avatar answered Dec 21 '22 22:12

Reinstate Monica


While WolframH's answer is the best answer for this case, a more general solution for finding overlaps is available, given you don't need to worry about repeated elements, which is to use sets and their intersection operation.

>>> set(range(10, 21)) & set(range(15, 26)) & set(range(18, 31))
{18, 19, 20}

Or, as a more general solution:

ranges = [(10, 20), (15, 25), (18, 30)]
set.intersection(*(set(range(start, finish+1)) for start, finish in ranges))
like image 24
Gareth Latty Avatar answered Dec 21 '22 23:12

Gareth Latty