20

尝试构建一个函数,该函数将返回 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 的情况。这显然是错误的。有没有一种简单的计算方法可以返回正确的值?

4

3 回答 3

50
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
于 2013-05-22T12:33:39.400 回答
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
于 2013-05-22T12:29:23.273 回答
1

在一维中,检查重叠的前提很简单(我认为)。找出较大的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
于 2013-05-22T12:32:11.450 回答