recursion to find odd numbers in a python list

1

I would like to know how to use recursion in Python to do a function that traverses all oddities in a list and append them to a new list

Tested the code to get 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:])

Output:

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

[DEBUG ON]

>>> 

Expected output:

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


>>> '[1,3]'

Debugger:

>'_main_'.encontra_impares(), line 14 if lista[0] % 2 == 0:
    
asked by anonymous 17.07.2017 / 20:25

2 answers

1

Doing 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])
  • The function encontra_impares is called with lista = [1, 2, 3] ;
  • Defines a local variable lis = [] ;
  • Verify that the length of lista is 1 and that the value is even. The length is 3, so run else ;
  • Checks whether the value in position 0 is even. No, because in position 0 is 1, which is odd, then if is not executed;
  • End of program?
  • Now 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 at Ideone .

        
    17.07.2017 / 20:54
    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

        
    17.07.2017 / 21:06