recursiveness to find odd numbers in a python list

Asked

Viewed 5,626 times

1

I would like to know how to use Python recursion to make a function that traverses all the odd notes from a list and add them to a new list

Tested the code I got a null output. I ran the Debugger and still could not find the reason. It stopped on line 14 (last line) and returned null, below the code is the output

My code so far:

def encontra_impares(lista):
    lis = []
    if len(lista) == 1 and lista[0] % 2 == 0:
        if not lista[0] % 2 == 0:
            return lis
        return lista
    else:
        if lista[0] % 2 == 0:
            return lista[0] + encontra_impares(lista[1:])

Exit:

>>> encontra_impares([1,2,3])

[DEBUG ON]

>>> 

Expected exit:

>>> encontra_impares([1,2,3])


>>> '[1,3]'

Debugger:

>'_main_'.encontra_impares(), line 14 if lista[0] % 2 == 0:
  • And what’s the problem with your code? You forgot to describe it in the question. Error? Which one? Did not fail but does not work? How did you test? What was the tested input? What was the output? What should be the output?

  • I had tested, the output is null, IE does not result in anything this code

  • Exactly. Edit the question and add what test you did explaining that the output was null and put what the output should have been.

2 answers

2


Making the Table test:

def encontra_impares(lista):
    lis = []
    if len(lista) == 1 and lista[0] % 2 == 0:
        if not lista[0] % 2 == 0:
            return lis
        return lista
    else:
        if lista[0] % 2 == 0:
            return lista[0] + encontra_impares(lista[1:])

encontra_impares([1,2,3])
  1. The function encontra_impares is called with lista = [1, 2, 3];
  2. A local variable is defined lis = [];
  3. The length of lista is 1 and if the value is even. The length is 3, then executes the else;
  4. Checks if the value at position 0 is even. No, because at position 0 is 1, which is odd, then the if;
  5. End of the program?

Now you understand why your program apparently crashed and the output is zero? A solution to the problem:

def encontra_impares(lista):

    # Define a lista que armazenará os números ímpares:
    lis = []

    # Verifica se há elementos na lista:
    if len(lista) > 0:

        # Retira o primeiro elemento da lista:
        numero = lista.pop(0)

        # Verifica se o número é ímpar:
        if numero % 2 != 0:

            # Sim, então adiciona-o à lista de ímpares:
            lis.append(numero)

        # Faz a união do resultado atual com o retorno para o resto da lista:
        lis = lis + encontra_impares(lista)

    # Retorna a lista final:
    return lis

See working on Ideone.

  • Putz, I forgot not. if not list[0] %2 == 0

  • thanks friend, now it makes sense. Recursion is a little bit difficult to understand

  • @l. martini then read about the table test and seek to make them in your codes. It will be much easier to understand.

2

def impares(l, i=0, lst_impares=[]):
    try:
        e = l[i] if l[i]%2!=0 else None
        i+=1
        if e:
            lst_impares.append(e)
        return impares(l,i,lst_impares) 
    except:
        return lst_impares

print(impares([1,2,3,4,5,19,10]))
[1, 3, 5, 19]

Run on repl.it

Browser other questions tagged

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