recursive function in python to calculate sum of elements of a list
I am having difficulty in an exercise whose I should show the sum of all elements of a list recursively.
The code I came up with only has the basis of recursion, the recursion itself I did not, as I did not understand how it could be applied to some list.
I'll leave the code here for you to analyze:
def soma_lista(lista):
if len(lista) == 1:
return lista[0]
else:
for i in range (len(lista)):
soma = lista[i] + soma_lista(lista[i + 1])
return soma
Note: as I said, I don't know how to apply the recursion part, so I tried something random. Ignore else's code block.
3 answers
Recursion in this case would play the role of the repeating loop, so you don't need to use both. Your recursion stop condition is correct: if the list has only one element, return it. already in else
, instead of the loop, you should return only the first element added with the function return to the rest of the list:
return lista[0] + soma_lista(lista[1:])
Where lista[1:]
returns the list from the first element. That is, the sum of a list will be equal to the first element summed with the result of the sum of the rest of the list and thus the recursion is done:
def soma_lista(lista):
if len(lista) == 1:
return lista[0]
else:
return lista[0] + soma_lista(lista[1:])
See working on Ideone.
Recursion is the technique where a method or function calls itself to arrive at the result.
I implemented this in Pythonic Form:
def soma_lista(lista=list()):
'''
Calcula a somatória dos elementos de uma lista.
:param lista: lista de elementos inteiros
:return: int
>>> soma_lista([1,2,3])
6
>>> soma_lista([1,2,3,4])
10
>>> soma_lista([1,2,3,4,5,6])
21
'''
try:
return lista.pop() + soma_lista(lista)
except IndexError:
return 0
if __name__ == '__main__':
import doctest
doctest.testmod()
print()
E this conventionally:
def soma_lista(lista=list()):
'''
:param lista:
:return:
>>> soma_lista([1,2,3])
6
>>> soma_lista([1,2,3,4])
10
>>> soma_lista([1,2,3,4,5,6])
21
'''
if len(lista) >= 1:
return lista.pop() + soma_lista(lista)
else:
return 0
if __name__ == '__main__':
import doctest
doctest.testmod()
print()
A way that I consider to be very didactic to show the" mysteries " of recursion in this case:
def recl(l, i=0):
try:
elmnt = l[i]
i+=1
return elmnt + recl(l,i)
except:
return 0
print (recl([1,2]))
3