我正在寻找一种简单的方法来使用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