Reputation: 1231
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 !
Upvotes: 4
Views: 2070
Reputation: 89007
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))
Upvotes: 4
Reputation: 4723
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
Upvotes: 8