recursive function in python to calculate sum of the elements of a list

4

I'm having a hard time in an exercise where I should show the sum of all elements of a list recursively.

The code that I just got has the basis of recursion, the recursion itself did not, because I did not understand how it could be applied to any list.

I'll leave the code here to review:

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 do not know how to apply the recursion part; so I tried something random. Ignore the else's code block.

    
asked by anonymous 17.07.2017 / 18:58

3 answers

4

Recursion, in this case, would play the role of repetition loop, so you do not need to use both. Its condition of stopping the recursion is correct: if the list has only one element, return it. In else , instead of the loop, you should only return the first element added with the function return for 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 at Ideone .

    
17.07.2017 / 19:11
0

Recursion is the technique where a method or function calls itself to get the result.

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 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()
    
17.07.2017 / 19:41
0

A form 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 on repl.it.

    
17.07.2017 / 19:48