简体   繁体   English

为什么这个return语句在这个python递归函数中抛出一个错误?

[英]Why does this return statement throw an error in this python recursive function?

I am practicing using recursive functions by summing all the elements in a list. 我通过对列表中的所有元素求和来练习使用递归函数。

The function I made was: 我的功能是:

def list_sum_recursive(input_list):

    #base case, list is empty
    if input_list == []:
        print("empty")
        return

    #recursive case
    else:
        #grab the first element
        head = input_list[0]
        del input_list[0]
        #return the sum of the head plus the sum of the rest of the list
        return head + list_sum_recursive(input_list)

This function throws this error however: 但是,此函数会抛出此错误:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType TypeError:+:'int'和'NoneType不支持的操作数类型

I did figure out the solution, making the base case return 0 instead of just return . 我确实找到了解决方案,使基本案例return 0而不是return

But now I'm curious what the plain return was, or wasn't, doing to throw an error? 但现在我很好奇普通的return是什么,或者不是,做错了? And why in python, a language that is pretty flexible and forgiving, such a thing is an issue? 为什么在python中,一种非常灵活和宽容的语言,这样的问题是一个问题?

As pointed out in the comments, don't return None in the first section. 正如评论中指出的那样,在第一部分中不要返回None。 Return 0 instead. 改为0。

def list_sum_recursive(input_list):

    #base case, list is empty
    if input_list == []:
    #    print("empty")
        return 0

    #recursive case
    else:
        #grab the first element
        head = input_list[0]
        del input_list[0]
        #return the sum of the head plus the sum of the rest of the list
        return head + list_sum_recursive(input_list)

print(list_sum_recursive([1,2,3]))

Running the program gives us 运行程序给了我们

$ python test.py
6

Just want to give you a more Pythonic version, I hope you don't mind. 只想给你一个更多的Pythonic版本,希望你不要介意。

def list_sum_recursive(input_list):

    #base case, list is empty
    if not input_list:
        return 0
    #return the sum of the head plus the sum of the rest of the list
    return input_list.pop(0) + list_sum_recursive(input_list)

print(list_sum_recursive([1,2,3]))
def list_sum_recursive(input_list):

    #base case, list is empty
    if input_list == []:
        print("empty")
        return

    #recursive case
    else:
        #grab the first element
        head = input_list[0]
        del input_list[0]
        #return the sum of the head plus the sum of the rest of the list
        x=list_sum_recursive(input_list)
        if(x==None):
            return head + 0
        else:
            return head+x

return 0 instead of none. 返回0而不是none。 or you can do this trick. 或者你可以做到这一点。

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

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