简体   繁体   English

如何通过递归获取数字列表的总和?

[英]How to get the sum of a list of numbers with recursion?

I want to sum numbers with a recursive function, ie我想用递归函数对数字求和,即

getSum([1, 2, 3, 4, 5]) 

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

I'm not an expert in recursive functions, I've tried something like:我不是递归函数方面的专家,我尝试过类似的方法:

def getSum(piece):
    for i in piece
        suc += getSum(i)

The problem is that I can't loop through integers.问题是我无法遍历整数。 I'm sure this is a quite easy task but I really can't figure it out.我确信这是一项非常简单的任务,但我真的无法弄清楚。

You don't need to loop.你不需要循环。 Recursion will do that for you.递归会为你做到这一点。

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

I think it is a little nicer without explicitly checking the length:我认为没有明确检查长度会更好一些:

def getSum(piece):
    return piece[0] + getSum(piece[1:]) if piece else 0

Demo:演示:

>>> getSum([1, 2, 3, 4, 5])
15

For academic purposes (learning Python) you could use recursion:出于学术目的(学习 Python),您可以使用递归:

def getSum(iterable):
    if not iterable:
        return 0  # End of recursion
    else:
        return iterable[0] + getSum(iterable[1:])  # Recursion step

But you shouldn't use recursion in real production code.但是您不应该在实际的生产代码中使用递归。 It's not efficient and the code much less clear then with using built-ins.与使用内置函数相比,它效率不高,而且代码也不那么清晰。 For this case you do not need neither recursion nor loop.对于这种情况,您既不需要递归也不需要循环。 Just use built-in sum :只需使用内置sum

>>>a = [1, 2, 3, 4, 5]
>>>sum(a) 
15

You can use reduce also.你也可以使用reduce。 The function reduce(func, seq) continually applies the function func() to the sequence seq.函数reduce(func, seq) 不断地将函数func() 应用于序列seq。 It returns a single value.它返回单个值。

reduce(lambda x,y: x+y, range(1,6))

using recursion and pop function使用递归和弹出函数

def getSum(piece):
    return piece.pop() + getSum(piece) if piece else 0

if your list is more complex than a simple list , for example:如果您的列表比简单列表更复杂,例如:

mylist = [1,-10,[[2,[3]],7.3],[[[[[[[[[-5]]]],2]]],1],4]]

you should use this code:你应该使用这个代码:

mylist = [1,-10,[[2,[3]],7.3],[[[[[[[[[-5]]]],2]]],1],4]]

def getSum(piece):
    if len(piece)==0:
        return 0
    elif type(piece[0]) is list:
        return getSum(piece[0]) + getSum(piece[1:])
    else:
        return piece[0] + getSum(piece[1:]) 
        
print(getSum(mylist))

Or, in a more "Pythonic" way:或者,以更“Pythonic”的方式:

suml = lambda l: l[0] + suml(l[1:]) if l else 0

print(suml(range(101)))

Output: 5050输出:5050

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

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