The Python Oracle

How to find range overlap in python?

This video explains
How to find range overlap in python?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Question
01:00 Accepted answer (Score 75)
01:34 Answer 2 (Score 120)
01:55 Answer 3 (Score 16)
02:13 Answer 4 (Score 13)
02:42 Thank you

--

Full question
https://stackoverflow.com/questions/6821...

Accepted answer links:
[requires both arguments to be sets]: https://docs.python.org/2/library/sets.h...

Answer 3 links:
[set]: http://docs.python.org/tutorial/datastru...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #range

#avk47



ANSWER 1

Score 151


If the step is always +1 (which is the default for range) the following should be more efficient than converting each list to a set or iterating over either list:

range(max(x[0], y[0]), min(x[-1], y[-1])+1)



ACCEPTED ANSWER

Score 83


Try with set intersection:

x = range(1,10)
y = range(8,20)
xs = set(x)
xs.intersection(y)   

Output:

set([8, 9])

Note that intersection accepts any iterable as an argument (y is not required to be converted to a set for the operation). There is an operator equivalent to the intersection method: & but, in this case, it requires both arguments to be sets.




ANSWER 3

Score 16


You can use sets for that, but be aware that set(list) removes all duplicate entries from the list:

>>> x = range(1,10)
>>> y = range(8,20)
>>> list(set(x) & set(y))
[8, 9]



ANSWER 4

Score 14


If you looking for the overlap between two real-valued bounded intervals, then this is quite nice:

def overlap(start1, end1, start2, end2):
    """how much does the range (start1, end1) overlap with (start2, end2)"""
    return max(max((end2-start1), 0) - max((end2-end1), 0) - max((start2-start1), 0), 0)

I couldn't find this online anywhere so I came up with this and I'm posting here.