Search code examples
pythonpython-3.xmathintersectionset-theory

Checking intersection of two sets by two values in each


I need to find out if there is any intersection between two arrays with start and end value (wiki on this https://en.wikipedia.org/wiki/Intersection_(set_theory)). For example (just a few cases):

a = (10, float("inf"))
b = (8, float("inf"))

or

a = (10, 20)
b = (4, 25)

So, b contains a. How can I do this in python ? Are there any tools for this ? Thanks


Solution

  • just test bounds:

    def contains(a,b):
        return a[0]>=b[0] and a[1]<=b[1]
    
    a = (10, 20)
    b = (4, 25)
    
    print(contains(a,b))
    
    a = (10, float("inf"))
    b = (8, float("inf"))
    
    print(contains(a,b))
    
    b = (80, float("inf"))
    
    print(contains(a,b))
    

    prints:

    True
    True
    False
    

    (as last test makes the condition false)

    As a side note, a python set is a collection of items, not a value range with start/stop as tuple, hence some possible confusion.

    Also note that your example is confusing. If you want intersection, not inclusion, define an intersect method like this:

    def intersects(a,b):
        return a[0] <= b[1] and b[0] <= a[1]