What is the best way in Python to determine what values in two ranges overlap?
For example:
x = range(1,10)
y = range(8,20)
(The answer I am looking for would be the integers 8 and 9.)
Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ranges? Thanks in advance for the help.
EDIT:
As a follow-up, I realized that I also need to know if x does or does not overlap y. I am looking for a way to iterate through a list of ranges and and do a number of additional things with range that overlap. Is there a simple True/False statement to accomplish this?
Assuming you are working exclusively with ranges, with a step of
1
, you can do it quickly with math.On a pair of ranges each with over 10^7 elements, this took under a second, independent of how many elements overlapped. I tried with 10^8 or so elements, but my computer froze for a while. I doubt you'd be working with lists that long.
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:
One option is to just use list comprehension like:
This is the answer for the simple range with step=1 case (99% of the time), which can be 2500x faster as shown in the benchmark when comparing long ranges using sets (when you are just interested in knowing if there is overlap):
To find the overlapping values:
Visual help:
Benchmark:
Conclusion: even for small ranges, it is twice as fast.
Conclusion: you want to use the range_overlapping function in this case as it is 2500x faster (my personal record in speedup)
If you want to find the overlap of ranges with arbitrary steps you can use my package https://github.com/avnr/rangeplus which provides a Range() class compatible with Python range(), plus some goodies including intersections:
Range() can also be unbound (when stop is None the Range goes on to +/-infinity):
The intersection is computed, not iterated, which makes the efficiency of the implementation independent of the length of the Range().
For "if x does or does not overlap y" :
result
Edit 1
Speeds comparison:
result
The ratio of these execution's times is 2.5