Python 求两个区间之间的整数距离
我正在寻找一种使用python查找两个整数间隔之间最小距离的简单方法。例如,[0,10]和[12,20]之间的最小值为2。如果两个间隔以任何方式重叠,则距离为0 有什么简单的建议吗?我忍不住想,一定有一个干净的“pythonic”方法来解决这个问题。Python 求两个区间之间的整数距离,python,integer,intervals,Python,Integer,Intervals,我正在寻找一种使用python查找两个整数间隔之间最小距离的简单方法。例如,[0,10]和[12,20]之间的最小值为2。如果两个间隔以任何方式重叠,则距离为0 有什么简单的建议吗?我忍不住想,一定有一个干净的“pythonic”方法来解决这个问题。def solve(r1,r2): def solve(r1, r2): # sort the two ranges such that the range with smaller first element # is assi
def solve(r1,r2):
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
#对两个范围进行排序,使第一个元素较小的范围
#分配给x,较大的分配给y
x、 y=已排序((r1,r2))
#现在,如果x[1]位于x[0]和y[0]之间(x[1]!=y[0],但可以等于x[0])
#然后范围不重叠,返回y[0]和x[1]的差
#否则返回0
如果x[0]>求解([0,10],[12,20])
2.
>>>求解([5,10],[1,5])
0
>>>求解([5,10],[1,4])
1.
希望以下内容能有所帮助:
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
def myDist(a,b):
如果a[0]+1。这个答案似乎很有效。显然,我已经厌倦了在脑海中直截了当地理解这一点>>我不太清楚*运算符对args做了什么,以及sorted()如何在两个列表上工作-您能解释一下吗?*在函数参数的上下文中,用于将参数值放在列表中,它通常用于可变数量的参数,但在这里,我们仍然可以在列表中使用它来保存一行代码。x,y=sorted(args)将列表扩展为两个变量x和y。这一切都是为了确保x小于y@DavidM我添加了一些解释。它将以无序的间隔失败:print solve((2,10),(11,8))#返回1
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