Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find range overlap in python?

Tags:

python

range

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?

like image 390
drbunsen Avatar asked Jul 25 '11 19:07

drbunsen


People also ask

How do you calculate overlap range?

1) Sort all intervals in increasing order of start time. This step takes O(nLogn) time. 2) In the sorted array, if start time of an interval is less than end of previous interval, then there is an overlap.

What is range overlap?

The level to which pay ranges in adjacent grades in a category overlap. Pay Range.

What is the syntax of range function in Python?

Syntax of range()start: integer starting from which the sequence of integers is to be returned. stop: integer before which the sequence of integers is to be returned. The range of integers ends at stop – 1. step: integer value which determines the increment between each integer in the sequence.


1 Answers

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) 
like image 119
Andrew Clark Avatar answered Sep 29 '22 18:09

Andrew Clark