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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With