Inverting sequence (PYTHON 3)

4

Good Night, I'm a beginner in IT and I'm doing a basic python course, I have to implement the following:

Write a program that receives a sequence of integers 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 not restrict 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 ???

    
asked by anonymous 23.03.2017 / 22:21

4 answers

4

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

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

seq.reverse()

Or simply:

seq = seq[::-1]
    
23.03.2017 / 22:45
2
seq = []
while True:
    numero = int(input())
    if (numero != 0):
        seq.append(numero)
    else:
        break

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

I made this way because I like to use while with breaks, but I would have to do in the same condition of the while, I hope I understood correctly what you want, if not, let me know if I change the answer. >     

23.03.2017 / 22:32
2

Problems:

  • The while n == 0 value will be an integer value and therefore is not iterable; doing seq[i] does not make sense at all.

  • A tip: To learn Python in the pythonic way you will need to get rid of any programming addiction you might 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, it traverses the whole list from back to front, with the function for i in seq[i] , displaying the values.

    You can see the code working here .

        
    23.03.2017 / 22:36
    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)
    
        
    05.07.2018 / 00:18