python - Get intersection range of two non-discrete intervals -
given interval defined start , end point (both floats), determine intersection range second interval. example:
int1 = [2. , 5.] int2 = [2.2, 7.] >>> desired_function(int1, int2) 2.8
it should handle intersection possibilities (no intersection, partial intersection, complete intersection, negative ranges etc.). attempt looks this:
def intersection(int1, int2): #case 1: partial intersection on left or right border if (int2[0]<=int1[0] , int2[1]<=int1[1]) or (int2[0]>=int1[0] , int2[1]>=int1[1]): return min(int1[1],int2[1]) - max(int1[0],int2[0]) #case 2: complete overlap of 1 interval other elif (int2[0]>=int1[0] , int2[1]<=int1[1]) or (int2[0]<=int1[0] , int2[1]>=int1[1]): return min (int2[1]-int2[0] , int1[1]-int1[0]) #case 3: no overlap @ else: return 0
question: have missed , there build-in solution or package similar since want keep code simple , fast possible?
you making things complicated, simple function is:
def interval_intersect(a,b): a0,a1 = b0,b1 = b return max(0,min(a1,b1)-max(a0,b0))
we calculate maximum of start of 2 intervals , minimum of end between these intervals. calculate difference , use max(0,...)
make sure if there no interval, return 0.
we can generalize function further into:
from operator import itemgetter def interval_intersect(*args): return max(0,min(map(itemgetter(1),args))-max(map(itemgetter(0),args)))
to let work arbitrary number of intervals. these both give:
>>> interval_intersect((2,5),(2.2,7)) 2.8
Comments
Post a Comment