4
I’m having difficulty in an exercise where I have to show the sum of all the elements of a list recursively.
The code I arrived has only the basis of the recursion, the recursion itself did not do, because 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 the Else code block.
hm, it makes sense. I thought recursion would only come to return the final results (list[-1]), I would never have imagined that it could work like the loop
– d. fritoti