The Python Oracle

How to find range overlap in python?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 How To Find Range Overlap In Python?
00:42 Accepted Answer Score 83
01:07 Answer 2 Score 16
01:21 Answer 3 Score 151
01:38 Answer 4 Score 14
01:56 Thank you

--

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

--

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.