How can I simply check if a range is a subrange of another ?
range1 in range2
will not work as expected.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With