尝试构建一个函数,该函数将返回2个线段之间的总重叠距离,用start和end int表示。
目前我有这个:我在某个地方上网,
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
这适用于0 100,0,20的情况,它返回100.这显然是错误的。 有一种简单的计算方法可以返回正确的值吗?
答案 0 :(得分:33)
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
答案 1 :(得分:6)
尚未完全测试,但如何 -
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
答案 2 :(得分:0)
在1-D中,检查重叠的前提很简单(我认为)。找到minimum
值中较大的值和maximum
值中较小的值。然后减去两个。
def overlap(min1, max1, min2, max2):
#Find out the bigger minimum
if min1 >= min2:
bigger_min = min1
else:
bigger_min = min2
if max1 >= max2:
smaller_max = max2
else:
smaller_max = max1
if smaller_max <= bigger_min:
return 0
else:
return smaller_max - bigger_min
结果
>>> overlap(20,40,30,70)
10
>>> overlap(0,100,200,300)
0
>>> overlap(0,100,0,30)
30
>>> overlap(0,100,30,60)
30
>>> overlap(0,100,30,70)
40
>>> overlap(20,100,30,70)
40
>>> overlap(20,30,30,70)
0
>>> overlap(0,50,0,50)
50