gpt4 book ai didi

Python递归函数不返回

转载 作者:行者123 更新时间:2023-11-28 20:18:44 25 4
gpt4 key购买 nike

<分区>

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

我用 Python 编写了以下代码,如果我在递归函数中放置一个“打印”命令以显示最终值,它可以正常工作,但它不会传递其返回值。最终结果是“无”。

为什么变量没有正确返回?

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com