Python递归函数不返回 [英] Python recursive function doesn't return

查看:45
本文介绍了Python递归函数不返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to sharpen my noob Python skills by trying a problem my son has in his college CS class. The goal is to create a function that uses recursion to process a list. The function must accept a list of arbitrary length and return a new list in which each element is the sum of itself and the elements to its right. So, if you input the list [5, 3, 2, 4], the function should return [14, 9, 6, 4].

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

I've written the following code in Python, and it works fine if I put a "print" command in the recursive function to show the final value, but it won't pass its return values. The end result is "None."

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

Why don't the variables return properly?

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.在下面查看您修改后的代码.

You need to actually return your RecursiveProcess. Look below at your modified code.

如果您所做的只是调用函数并将值存储在 ListIn2 中,那么您并没有完全递归地执行任何操作.您将继续覆盖以前的数据.通过返回,您最终会得到递归行为:

You aren't exactly doing anything recursively if all you do is call the function and store the value in ListIn2. You will keep overwriting your previous data. By returning, you will end up getting your recursive behaviour:

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]

这篇关于Python递归函数不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆