is there a built in function to compute the overlap between two discrete intervals, e.g. the overlap between [10, 15] and [20, 38]? In that case the overlap is 0. If it's [10, 20], [15, 20], the overlap is 5.
thanks.
is there a built in function to compute the overlap between two discrete intervals, e.g. the overlap between [10, 15] and [20, 38]? In that case the overlap is 0. If it's [10, 20], [15, 20], the overlap is 5.
thanks.
You can use max and min:
>>> def getOverlap(a, b):
... return max(0, min(a[1], b[1]) - max(a[0], b[0]))
>>> getOverlap([10, 25], [20, 38])
5
>>> getOverlap([10, 15], [20, 38])
0
Check out pyinterval http://code.google.com/p/pyinterval/
import interval
x=interval.interval[10, 15]
y=interval.interval[20, 38]
z=interval.interval[12,18]
print(x & y)
# interval()
print(x & z)
# interval([12.0, 15.0])
You could use set intersections, as you would in mathematics:
x = set(range(10, 15))
y = set(range(20, 38))
len(x.intersection(y))
0
x = set(range(10, 20))
y = set(range(15, 20))
len(x.intersection(y))
5
You can even inspect the intersection if you need to: x.intersection(y)