Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a range is a part of another range in Python 3.x

How can I simply check if a range is a subrange of another ?

range1 in range2 will not work as expected.

like image 564
mr.wolle Avatar asked Sep 09 '15 13:09

mr.wolle


People also ask

How do you check if a range is in another range Python?

To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.

How do you check if a number is between two values in Python?

Use the comparison operators to check if a number is between two numbers. Use the syntax minimum <= number <= maximum such that maximum is greater than minimum to return a boolean indicating whether number falls between minimum and maximum on a number line.

Is range in Python inclusive?

Python range is inclusive because it starts with the first argument of the range() method, but it does not end with the second argument of the range() method; it ends with the end – 1 index.


1 Answers

You can do it in O(1), as follows:

def range_subset(range1, range2):
    """Whether range1 is a subset of range2."""
    if not range1:
        return True  # empty range is subset of anything
    if not range2:
        return False  # non-empty range can't be subset of empty range
    if len(range1) > 1 and range1.step % range2.step:
        return False  # must have a single value or integer multiple step
    return range1.start in range2 and range1[-1] in range2

In use:

>>> range_subset(range(0, 1), range(0, 4))
True
like image 179
jonrsharpe Avatar answered Oct 01 '22 03:10

jonrsharpe