Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 299
H. Hasin Avatar asked Feb 04 '16 07:02

H. Hasin


3 Answers

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])
like image 183
vks Avatar answered Oct 02 '22 07:10

vks


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
like image 34
timgeb Avatar answered Oct 02 '22 06:10

timgeb


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
like image 26
The Godfather Avatar answered Oct 02 '22 07:10

The Godfather