Given the min and max of two ranges, is the second range contained in the first?

Question:

Given the min and max values of two ranges representing continuous intervals, I want to know if the second range is within the first. Note also that this question has nothing whatsoever to do with Python’s range function.

Note that I don’t have the start and end of each range. I am already receiving the min and max from upstream. There exist some similar questions, but they do not use min and max, and they don’t distinguish between non-strict vs strict. I would like the simplest possible logic.

To give a natural example, when a person is standing, the range of one’s waist to knee is contained in the larger range of head to toe. The range of head to waist is however not contained in the range of neck to knee.

More formally, this can be checked non-strictly or strictly as per the tests below:

Non-strict:

def is_subrange(min1, max1, min2, max2):
    ...  # To be implemented.

assert is_subrange(2, 9, 5, 7) == True
assert is_subrange(2, 9, 1, 3) == False
assert is_subrange(2, 9, 7, 11) == False
assert is_subrange(2, 9, 1, 11) == False

assert is_subrange(2, 9, 6, 9) == True  # is not strict
assert is_subrange(2, 9, 2, 4) == True  # is not strict
assert is_subrange(2, 9, 2, 9) == True  # is not strict

Strict:

def is_strict_subrange(min1, max1, min2, max2):
    ...  # To be implemented.

assert is_strict_subrange(2, 9, 5, 7) == True  # is as is_subrange
assert is_strict_subrange(2, 9, 1, 3) == False  # is as is_subrange
assert is_strict_subrange(2, 9, 7, 11) == False  # is as is_subrange
assert is_strict_subrange(2, 9, 1, 11) == False  # is as is_subrange

assert is_strict_subrange(2, 9, 6, 9) == False  # is not as is_subrange
assert is_strict_subrange(2, 9, 2, 4) == False  # is not as is_subrange
assert is_strict_subrange(2, 9, 2, 9) == False  # is not as is_subrange
Asked By: Asclepius

||

Answers:

This might help.

def is_subrange(min1, max1, min2, max2):
    return min1 <= min2 and max1 >= max2


def is_strict_subrange(min1, max1, min2, max2):
    return min1 < min2 and max1 > max2
Answered By: Murali S
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.