python recursive function to compute sum of the elements of a list

Asked

Viewed 4,922 times

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.

3 answers

4


A recursion, in this case, would play the role of the repeat loop, so you don’t need to use both. Your recursive stop condition is correct: if the list has only one element, return it. No else, instead of the loop, you should return only the first element added with the return of the function 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 added with the result of the sum of the rest of the list and thus recursion is made:

def soma_lista(lista):
    if len(lista) == 1:
        return lista[0]
    else:
        return lista[0] + soma_lista(lista[1:])

See working on Ideone.

  • 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

0

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()

And this one in a conventional way:

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()
  • Can you explain why using the exception would be the pythonica form? I honestly can’t see why. In fact, to say that pythonica is a solution that makes the sum of elements of a list with recursion no longer makes any sense.

  • The premise of Pythonic Mode says it’s better to ask for forgiveness than permission. So instead of checking for an element in the list before running, simply run. And if there is an exception, treat it. E in this case will be when there are no more items in the list. Which are removed during pop method execution().

  • Can you tell me the source of this premise?

  • EAFP (Easier to Ask Forgiveness than Permission) - "better to ask forgiveness than to ask permission", available at https://docs.python.org/2/glossary.html. Here also: https://stackoverflow.com/questions/32901886/why-is-it-easier-to-ask-forgiveness-than-it-permission-to-get-permission-in-python

  • In the words of Guido van Rossun: "and I disagree with the position that EAFP is Better than LBYL, or "generally Recommended" by Python.". Still, if you want to comment on this at What is a "pythonic" code?

0

A way that I consider to be well 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

Run the code in repl.it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.