Returning the inverse of a recursive sequence of numbers in Python

Asked

Viewed 76 times

-1

Well, it follows my code that aims to find the inverse of a list in python through recursive

def inverso(n, seq):
    if len(seq) == 0:
        return
    else:
        ultimo_valor = seq[n-1]
        print(ultimo_valor, end=' ')
        seq.pop()
        inverso((n-1), seq)
        

n = int(input())
sequencia = []
for c in range(n):
    if n >= 1 and n <= 100:
        sequencia.append(int(input()))
print(inverso(n, sequencia))


The problem arises at the moment that is appearing a None at the end, thing that was not supposed to appear

#entrada
5 #tamanho da sequencia
1
3
6
4
3
#saída
3 4 6 3 1

The output must be on the same line and separated by a space. Thanks in advance.

  • Okay, thank you. In my case it’s the other way around.

  • 1

    The answer is simpler than it looks. During its inverse function it performs prints, but returns no value. Then when you print a function that does not return any value, the 'None' will appear. Try calling the recursive function out of print to see the result.

1 answer

5


If you can make it simple.

print('Digite uma lista de inteiros separados por espaço:')
sequencia = [int(e) for e in input().split(" ")]

sequencia.reverse()

print(" ".join([str(e) for e in sequencia]))

Now if you really need to use recursion continue on the simple.

def reverter(l):
  #Se a l estiver vazia apenas retorna []
  if len(l) == 0: return []
  #Devolve o último elemento de l mais o reverso da fatia que vai do 
  #primeiro elemento ao penúltimo elemento inclusive
  return [l[-1]] + reverter(l[:-1]) 

print('Digite uma lista de inteiros separados por espaço:')
sequencia = [int(e) for e in input().split(" ")]

sequencia = reverter(sequencia)

print(" ".join([str(e) for e in sequencia]))

Test the example on Repl.it

Browser other questions tagged

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