Python,使用递归获取数字列表的总和

H. *_*sin 4 python recursion

我想用递归函数对数字求和,即

getSum([1, 2, 3, 4, 5]) 
Run Code Online (Sandbox Code Playgroud)

应该返回1 + 2 + 3 + 4 + 5 == 15

我不是递归函数的专家,我尝试过类似的方法:

def getSum(piece):
    for i in piece
        suc += getSum(i)
Run Code Online (Sandbox Code Playgroud)

问题是我无法遍历整数。我敢肯定这是一件很容易的事,但我真的不知道。

vks*_*vks 6

您不需要循环。递归将为您做到这一点。

def getSum(piece):
    if len(piece)==0:
        return 0
    else:
        return piece[0] + getSum(piece[1:]) 
print getSum([1, 3, 4, 2, 5])
Run Code Online (Sandbox Code Playgroud)


tim*_*geb 6

我认为没有明确检查长度会更好一些:

def getSum(piece):
    return piece[0] + getSum(piece[1:]) if piece else 0
Run Code Online (Sandbox Code Playgroud)

演示:

>>> getSum([1, 2, 3, 4, 5])
15
Run Code Online (Sandbox Code Playgroud)