tags:

views:

165

answers:

3

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.

+8  A: 

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
Mark Byers
seems pretty neat
Matt Joiner
+3  A: 

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])
unutbu
+1 Because I didn't know about that module, though it might be overkill if he just needs it for this one calculation.
Mark Byers
The OP was looking for "a built in function".
Johnsyweb
+1  A: 

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)

Johnsyweb
-1. What if you had to find the intersection of [0, 10^9] and [10^9+1,10^10]? that's O(n) space and O(n) time for an almost trivial task that can be done in constant time.
ooboo
@ooboo: Thank you, the complexity is very much worth pointing out for the OP choosing an implementation. Not sure it's worth a -1, though. Some people optimise for CPU cycles, other optimise for code readability. I merely provided a solution.
Johnsyweb
I think that the original solution should be clear to anyone who knows basic arithmetic, and it could be the difference between a blink of an eye and a completely unfeasible task in the example I gave...
ooboo