The function returns None although the variable saves the correct result

Asked

Viewed 47 times

2

I must do a function that returns the odd elements of a list using recursion. I saved the list with the odd ones in the variable I, and when return this variable the result is None.

def encontra_impares(lista, indice=0,I=[]):
 if indice >len(lista)-1:
    return I
 else:
    
    testa=lista[indice]%2
    
    if testa != 0:
        I.append(lista[indice])
        
    indice += 1
    encontra_impares(lista,indice,I)
  • 1

    You do not assign the function return to anything. Try, for example: print(encontra_impares(lista,indice,I)) and evaluate the result.

1 answer

1

Missed you return recursive call result:

def encontra_impares(lista, indice=0,I=[]):
    if indice > len(lista) - 1:
        return I
    else:
        if lista[indice] % 2 != 0:
            I.append(lista[indice])
        indice += 1
        return encontra_impares(lista, indice, I) # <--- aqui

print(encontra_impares([1, 2, 3, 4, 5])) # [1, 3, 5]

When you just call the function (without the return), it is called and the return is ignored because you do nothing with it (and when the function ends without finding a return, she ends up returning None).


Just for the record, you can also do it without needing an index, or an accumulator list:

def encontra_impares(lista):
    if not lista: # lista vazia
        return []
    if lista[0] % 2 != 0:
        return [ lista[0] ] + encontra_impares(lista[1:])
    return encontra_impares(lista[1:])

The idea is:

  • if the list is empty, returns an empty list
  • otherwise, check whether the first element is odd
    • if it is, it returns the result of encontra_impares(lista[1:]) (whereas lista[1:] is a "sub-list" containing the second element on)
    • if not odd, returns only the odd of the rest of the list

But of course recursion is not the best way to solve it. The simplest is using a loop even:

def encontra_impares(lista):
    impares = []
    for n in lista:
        if n % 2 != 0:
            impares.append(n)
    return impares

# ou usando list comprehension
def encontra_impares(lista):
    return [ n for n in lista if n % 2 != 0 ]

Browser other questions tagged

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