How to get the sum of a list of numbers with recursion?
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
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])