H. Hasin
H. Hasin

Reputation: 197

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.

Upvotes: 12

Views: 62501

Answers (8)

Svir
Svir

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

Reza Abdollahi
Reza Abdollahi

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

Vlad Bezden
Vlad Bezden

Reputation: 89499

using recursion and pop function

def getSum(piece):
    return piece.pop() + getSum(piece) if piece else 0

Upvotes: 0

Tuna Durnal
Tuna Durnal

Reputation: 11

Or, in a more "Pythonic" way:

suml = lambda l: l[0] + suml(l[1:]) if l else 0

print(suml(range(101)))

Output: 5050

Upvotes: 0

okainov
okainov

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

vks
vks

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

timgeb
timgeb

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

WISHTO
WISHTO

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

Related Questions