Reputation: 197
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
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.
Upvotes: 12
Views: 62501
Reputation: 1
Somthing like this:
def rec_sum(array):
total = 0
if len(array):
total += array.pop(0) + rec_sum(array)
return total
Upvotes: 0
Reputation: 481
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))
Upvotes: 1
Reputation: 89499
using recursion and pop function
def getSum(piece):
return piece.pop() + getSum(piece) if piece else 0
Upvotes: 0
Reputation: 11
Or, in a more "Pythonic" way:
suml = lambda l: l[0] + suml(l[1:]) if l else 0
print(suml(range(101)))
Upvotes: 0
Reputation: 4658
For academic purposes (learning Python) you could use recursion:
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:
>>>a = [1, 2, 3, 4, 5]
>>>sum(a)
15
Upvotes: 3
Reputation: 67968
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])
Upvotes: 20
Reputation: 78650
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
Upvotes: 8
Reputation: 88
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(lambda x,y: x+y, range(1,6))
Upvotes: 2