找到两个间隔之间的整数距离

时间:2013-05-30 18:27:39

标签: python integer intervals

我正在寻找一种使用python找到两个整数间隔之间的最小距离的简单方法。例如,[0,10]和[12,20]之间的最小值为2.如果两个间隔以任何方式重叠,则距离将为0.

有关简单方法的任何建议吗?我不禁想到必须有一个干净的,“pythonic”的方式来解决这个问题。

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

dist=min(y)-max(x)
if dist>0:
    return dist
else:
    return 0

答案 2 :(得分: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

祝你好运!!!