Given an interval defined by a start and end point (both floats), I would like to determine the intersection range with a second interval. For example:
int1 = [2. , 5.]
int2 = [2.2, 7.]
>>> desired_function(int1, int2)
2.8
It should handle all intersection possibilities (no intersection, partial intersection, complete intersection, also negative ranges etc.). My attempt looks like this:
def intersection(int1, int2):
#case 1: partial intersection over the left or right border
if (int2[0]<=int1[0] and int2[1]<=int1[1]) or (int2[0]>=int1[0] and int2[1]>=int1[1]):
return min(int1[1],int2[1]) - max(int1[0],int2[0])
#case 2: complete overlap of one interval by the other
elif (int2[0]>=int1[0] and int2[1]<=int1[1]) or (int2[0]<=int1[0] and int2[1]>=int1[1]):
return min (int2[1]-int2[0] , int1[1]-int1[0])
#case 3: no overlap at all
else:
return 0
Question: Have I missed something and is there any build-in solution or package that does something similar since want to keep my code as simple and fast as possible?