How to find range overlap in python?
Solution 1:
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)
Solution 2:
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.
Solution 3:
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]
Solution 4:
One option is to just use list comprehension like:
x = range(1,10)
y = range(8,20)
z = [i for i in x if i in y]
print z
Solution 5:
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.