Trying to build a function that will return the total overlapping distance between 2 line segments, denoted by start and end ints.
Currently I have this: That I got off the internet somewhere,
def overlap(min1, max1, min2, max2):
"""returns the overlap between two lines that are 1D"""
result = None
if min1 >= max2 or min2 >= max1: result = 0
elif min1 <= min2:
result = max1 - min2
else: result = max2 - min1
return result
This works however for the case of 0 100, 0,20 it returns 100. And that's clearly wrong. Is there a simple way of calculating this that will return the correct values?
def overlap(min1, max1, min2, max2):
return max(0, min(max1, max2) - max(min1, min2))
>>> overlap(0, 10, 80, 90)
0
>>> overlap(0, 50, 40, 90)
10
>>> overlap(0, 50, 40, 45)
5
>>> overlap(0, 100, 0, 20)
20
Not fully tested, but how about -
def overlap(min1,max1,min2,max2):
start = max(min1,min2)
end = min(max1,max2)
d = end - start
if d < 0:
return 0
else:
return d
#some tests
print overlap(0,100,0,20)
print overlap(5,10,15,20)
print overlap(1,3,0,5)
print overlap(-5,5,-2,10)
>>>
20
0
2
7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With