Inverting sequence (PYTHON 3)

Asked

Viewed 23,719 times

8

I have to implement the following:

Write a program that takes a sequence of integer numbers ending with 0 and prints all values in reverse order. **Note that 0 (ZERO) should not be part of the sequence.

Example:

Digite um número: 1
Digite um número: 7
Digite um número: 4
Digite um número: 0

4
7
1

I made the following code, but I can’t narrow it down to 0.

seq = []
i = 1

while i > 0:
    n = int(input("Digite n: "))    
    seq.append(n)

    while n == 0:

        for i in seq[i]:

            print (i)
            i -= 0

Could someone tell me what I did wrong???

9 answers

12

If you want to have a Pythonic style of programming, you can do so:

To read the data you can consider the example of our friend Arcashaid. Following with the inverter part of the list, see how elegant it is in pythonic style:

seq.reverse()

Or simply:

seq = seq[::-1]
  • Thank you Andrey.

  • 2

    It is worth noting that both methods create a new list in memory and, if seq is very large, can bring harm to the application, while using the function reversed creates a Generator, consuming little memory independent of list size.

  • Very well placed @Andersoncarloswoss

7

Problems:

  1. The excerpt while n == 0 will produce an infinite loop and so will print infinitely numbers on the screen (we do not want this).

  2. The value seq[i] will be an entire value and therefore is not eternal; do for i in seq[i] doesn’t make any sense.

A tip: to learn Python pythonic you will need to get rid of any programming addiction you may have with other languages.

I would solve your problem like this:

# Lista de valores:
seq = []

# Executa até ocorrer `break`
while True:

    # Pede ao usuário um valor inteiro:
    n = int(input("Digite n: "))    

    # Se for zero, pare o loop:
    if n == 0: break

    # Se não, adiciona o valor a lista:
    seq.append(n)

# Percorre toda a lista de trás para frente:
for i in reversed(seq):

    # Exibe o valor na tela:
    print(i)

With an infinite loop you read the values until you find zero, while adding them to the list. At the end, go through the entire list backwards, with the function reversed, displaying the values.

You can see the code working here.


In version 3.8 of Python was added to assignment Expression which would simplify the above code, which generates a list of values from the entry until the number 0 is informed:

seq = []

while (n := int(input('Digite n: '))) != 0:
    seq.append(n)

The list seq will have all the numbers informed until the value 0 is informed. Only one care should be taken regarding the validation of the input, because the structure int throws an exception ValueError if the given value is not numerical; the exception is not being treated in the example.

2

seq = []
while True:
    numero = int(input())
    if (numero != 0):
        seq.append(numero)
    else:
        break

for i in seq[::-1]:
    print (i)

I did so because I like to use while with breaks, but would be able to do in the same condition of while, I hope to have understood right what you want, if it is not that let me know I modify the answer

0

From what I understand, the number 0 shall not be counted or entered in the list. In this case, the 0 will only function as flag stop, that is, when the value is entered "0", normal program flow will be terminated. From this moment, the program will display all previously typed values in reverse order, except for the value "0".

To resolve this issue can be used the following code:

lista = list()
while True:
    n = int(input(f'Digite um número: '))

    if n != 0:
        lista.append(n)
    else:
        cont = 0
        while len(lista) >= 1:
            print(lista[-1])
            del(lista[-1])
            cont -= 1
        break

Note that when a value is entered, the program checks whether it is diferente of "0". If different from "0", this value shall be inserted in list and the laço de repetição - that feeds the list - will be restarted. Otherwise, the repeat loop will be closed and the list will be displayed in reverse order without the value "0".

Also note that, who controls the exibição of the list elements is 2º while. For this, it checks whether the list size is greater than or equal to "1". If so, the last item in the list is displayed (lista[-1]). Then delete that item from the list and decrement the counter. Then this whole process is redone until the initial list has no more elements.

Another way to resolve this issue would be:

lista = list()
while True:
    n = int(input(f'Digite um número: '))

    if n != 0:
        lista.append(n)
    else:
        for c in sorted(lista, reverse=True):
            print(c)
        break

0

The code stays in the loop while n is non-zero, leaves when n=0 and does not add zero to the list. Follow the code

seq = []
#inicia n com 1 para entrar no loop
n = 1

while n:
    n = int(input("Digite n: "))
    # só adiciona na lista se for diferente de zero
    if n!=0 : seq.append(n)
print(seq)
# para inverter uma lista, é só usar [::-1]
print(seq[::-1])

The exit was left:

Digite n: 1
Digite n: 2
Digite n: 3
Digite n: 4
Digite n: 5
Digite n: 0
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

0

#reverse only one number

n = input("Digite um número:")
print (''.join(reversed(n)))

#invert letters (of a word)

n = input("Digite uma Palavra:")
print (''.join(reversed(n)))

0

def numReverse(n,numInv = 0):
  while n > 0:
    resto = n % 10
    n = n // 10
    numInv = numInv * 10 + resto
  print(numInv)

example uses

numReverse(123)
numReverse(918273563)

-1

retorne = input("Digite seu número: ") 

def InverterNum():
    reverter =[]
    reverter.extend(retorne)
    reverter.reverse()

    revertido = str(reverter).strip('[]')
    revertido = ''.join(reverter)

    return revertido

ver = print("Seu número invertido: " + InverterNum())

-2

This solution is working, however, not the most optimized.

def inverte_ordem():
    lista = []
    l2 = []
    n = 1
    i = 0
    while n != 0:
        n = int(input('Digite um numero: '))
        lista.append(n)
        i = len(lista)
    i = i - 1
    while i >= 0:
        l2.append(lista[i])
        i = i - 1
    for a in l2:
        if a != 0:
            print(a)

x = inverte_ordem()

Browser other questions tagged

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