[英]Finding the minimum difference between two elements with recursion
I'm trying to make a "shortest distance algorithm for 1D".我正在尝试制作“一维最短距离算法”。
However, I'm confused on the recursive case.但是,我对递归情况感到困惑。 I don't know how to get the value back after the recursive calls (lines 14 and 15).我不知道如何在递归调用后取回值(第 14 和 15 行)。 How can I fix the following code?我该如何修复以下代码?
def recCPairDist(points):
if len(points) == 1:
return 0
elif len(points)== 2:
abs(points[1]-points[0])
#how do i assign the result final value back to "leftDist rightDist"
#since its a recurisive, the result can be more than 1, should i store all the result in a list first?
#then get the min(list)?
else:
mid = len(points) // 2
first_half = points[:mid]
second_half = points[mid:]
leftDist = recCPairDist(first_half)
rightDist = recCPairDist(second_half)
midDist = abs(second_half[0] - first_half[1]) #i dont think this is correct since i didnt consider the recursion
return min(leftDist,rightDist,midDist)
def cPairDist(points):
points.sort()
return recCPairDist(points)
P1 = [7, 4, 12, 14, 2, 10, 16, 6]
cPairDist(P1)
The expected result for P1 should be 1, since the shortest distance would be between 7 and 6. P1 的预期结果应为 1,因为最短距离介于 7 和 6 之间。
You're really close: There's three things you have to do:你真的很接近:你必须做三件事:
0
.对于只有一点需要考虑的情况,您不应该返回0
。 For example, for the array [3, 6, 9]
, the answer is 3, but your given base case will return 0
.例如,对于数组[3, 6, 9]
,答案是 3,但您给定的基本情况将返回0
。 This is because one of the resulting subarrays will be of length 1 for odd-length arrays, and the zero return value will propagate when you return from each recursive call.这是因为对于奇数长度 arrays,生成的子数组之一的长度为 1,并且当您从每个递归调用返回时将传播零返回值。abs(points[1]-points[0])
in the len == 2
base case explicitly using the return
keyword.您需要在len == 2
基本情况下使用return
关键字显式返回值abs(points[1]-points[0])
。midDist
should compute this value.所以,您的midDist
应该计算这个值。Here is a code snippet that resolves all three of these issues:这是解决所有这三个问题的代码片段:
def recCPairDist(points):
if len(points) == 1:
return float('inf')
elif len(points)== 2:
return abs(points[1]-points[0])
else:
mid = len(points) // 2
first_half = points[:mid]
second_half = points[mid:]
leftDist = recCPairDist(first_half)
rightDist = recCPairDist(second_half)
midDist = abs(first_half[-1] - second_half[0])
return min(leftDist,rightDist,midDist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.