我正在寻找一种简单的方法来使用 python 找到两个整数间隔之间的最小距离。例如,[0,10] 和 [12,20] 之间的最小值将为 2。如果两个区间以任何方式重叠,则距离将为 0。
有什么简单的方法可以做到这一点吗?我不禁认为必须有一种干净的“pythonic”方式来解决这个问题。
def solve(r1, r2):
# sort the two ranges such that the range with smaller first element
# is assigned to x and the bigger one is assigned to y
x, y = sorted((r1, r2))
#now if x[1] lies between x[0] and y[0](x[1] != y[0] but can be equal to x[0])
#then the ranges are not overlapping and return the differnce of y[0] and x[1]
#otherwise return 0
if x[0] <= x[1] < y[0] and all( y[0] <= y[1] for y in (r1,r2)):
return y[0] - x[1]
return 0
...
>>> solve([0,10],[12,20])
2
>>> solve([5,10],[1,5])
0
>>> solve([5,10],[1,4])
1
dist=min(y)-max(x)
if dist>0:
return dist
else:
return 0
希望以下内容有所帮助:
def myDist(a,b):
if a[0] <= a[1] < b[0]:
return b[0] - a[1]
if b[0] <= b[1] < a[0]:
return a[0] - b[1]
return 0
祝你好运!!!