繁体   English   中英

Python递归函数不返回

[英]Python recursive function doesn't return

我正在尝试通过解决儿子在大学CS班上遇到的问题来提高我的noob Python技能。 目标是创建一个使用递归处理列表的函数。 该函数必须接受任意长度的列表,并返回一个新列表,其中每个元素都是其自身及其右边元素的总和。 因此,如果输入列表[5、3、2、4],该函数应返回[14、9、6、4]。

我已经用Python编写了以下代码,如果我在递归函数中输入“ print”命令以显示最终值,则它可以很好地工作,但它不会传递其返回值。 最终结果是“无”。

为什么变量不能正确返回?

def RecursiveProcess(ListIn2, target): #Recursive function that adds to target value the value to its right
    if target > -1:  #stop function if index is below 0
        ListIn2[target] = ListIn2[target] + ListIn2[target+1]  #Add value to the right of target to the target value 
        ListIn2 = RecursiveProcess(ListIn2, target-1) #Call the function again with lower taget value to process the next value
    else:
        return ListIn2  #return the changed list

def ProcessList(ListIn):  #helper function to pass the list and the position of penultimate value
    return RecursiveProcess(ListIn, len(ListIn)-2) #return the changed list

print ProcessList([5, 10, 11, 6, 7, 1, 2, 4, 6, 7])  #initiate recursion and print result

您实际上需要返回RecursiveProcess 在下面查看您修改后的代码。

如果您要做的只是调用该函数并将值存储在ListIn2则您没有递归地执行任何ListIn2 您将继续覆盖以前的数据。 通过返回,您将最终获得递归行为:

def RecursiveProcess(ListIn2, target): #Recursive function that adds to target value the value to its right
    if target > -1:  #stop function if index is below 0
        ListIn2[target] = ListIn2[target] + ListIn2[target+1]  #Add value to the right of target to the target value
        return RecursiveProcess(ListIn2, target-1) #Call the function again with lower taget value to process the next value
    else:
        return ListIn2  #return the changed list

l = [5, 10, 11, 6, 7, 1, 2, 4, 6, 7]
d = RecursiveProcess(l, len(l)-2)
print(d) # [59, 54, 44, 33, 27, 20, 19, 17, 13, 7]

问题是您实际上并没有进行递归操作(每次对同一函数的调用都会返回结果),但是由于列表是可变的,因此您不需要:

def ProcessList(ListIn):
    RecursiveProcess(ListIn, len(ListIn)-2) #this will change the list in place!
    return ListIn

这就是让它按预期工作的全部方法。 因为每个元素都是在“递归”中更新的,所以不需要将指针传递到列表周围。 结果也是预期的:

# [59, 54, 44, 33, 27, 20, 19, 17, 13, 7]

您一般不会回来。 尝试:

def RecursiveProcess(ListIn2, target): 
    if target > -1:
        ListIn2[target] = ListIn2[target] + ListIn2[target+1]  
        ListIn2 = RecursiveProcess(ListIn2, target-1) 
        return ListIn2 #Actually need to return in the general case
    else:
        return ListIn2  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM