In: Computer Science
In Python
iOverlap (a1, a2, b1, b2)
Write the function iOverlap that tests whether 2 closed intervals overlap. It takes 4 numbers (ints or floats) a1, a2, b1, b2 that describe the two closed intervals [a1,a2] and [b1,b2] of the real number line, and returns True if these two closed intervals overlap (even if at only one point) and False otherwise. If a1>a2, then the interval [a1,a2] is empty. If b1>b2, then the interval [b1,b2] is empty. Both intervals are closed, so contain their endpoints. For example, the intervals [1,2] and [2,3] overlap at the point 2.
def iOverlap (a1, a2, b1, b2): if a1 >= a2 or b1 >= b2: return False else: return (a1 >= b1 and a2 <= b2) or (b1 >= a1 and b2 <= a2) or (a1 <= b1 <= a2) or (b1 <= a1 <= b2) print(iOverlap(1, 2, 2, 3))