Python,通过递归获取数字列表的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35194767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, get sum of a list of numbers with recursion
提问by H. Hasin
I want to sum numbers with a recursive function, i.e.
我想用递归函数对数字求和,即
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.
问题是我无法遍历整数。我确信这是一项非常简单的任务,但我真的无法弄清楚。
采纳答案by vks
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])
回答by WISHTO
You can use reduce also. The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.
你也可以使用reduce。函数reduce(func, seq) 不断地将函数func() 应用于序列seq。它返回单个值。
reduce(lambda x,y: x+y, range(1,6))
回答by The Godfather
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
回答by timgeb
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
回答by Tuna Durnal
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
回答by Vlad Bezden
using recursion and pop function
使用递归和弹出函数
def getSum(piece):
return piece.pop() + getSum(piece) if piece else 0