Can you do with fewer variables?

0

Constructing a program asks the user to enter positive integers, terminated by 0, and whose output is: "yes X", without the quotation marks, if the sequence contains positive values X and form an increasing sequence; otherwise print "no X".

a = int(input("Digite o primeiro valor da sequencia: "))
b = int(input("Digite o segundo valor da sequencia: "))

i=1

if a == 0:
    print("nao ", 0)
if a>0 and b == 0:
    print("sim ", 1)

while a>0 and b>0:
    i=2
    c = int(input("Digite outro valor da sequencia: "))
    if c>b:
        i = i + 1
    if c<b:
        i = i + 1
    a = int(input("Digite algum outro valor da sequencia: "))
    b = a
    c = b
    a = c

if a == 0 and c>b:
    print("sim ", i)
if a == 0 and c<b:
    print("nao ", i)
if c == 0 and c>b:
    print("sim ", i)
if c==0 and b<c:
    print("nao ", i)
    
asked by anonymous 03.04.2018 / 03:05

2 answers

0

Hello, I do not know if you have already learned about lists in python but there is a very simple code And I did not understand why you want me to print 'yes, X' and 'no, X' but I inserted it there. I assign it to the variable sequence '[]' thus saying it will be a list, and I made a simple loop whenever True it will continue if a is equal to '0' it gives a break in the loop otherwise it adds to the list with the .append () method is the variable a. At the end it prints the list. sorted (X) == sorts the X (a list) incrementally. I hope I have helped.

sequencia = []
x = 0
while True:
    a = int(input('Digite o valor'))
    if a == 0:
        print('não', x)
        break
    else:
        print('sim', x)
        sequencia.append(a)
    x += 1




print(sorted(sequencia))
    
04.04.2018 / 14:21
0

To read the sequence, just modify the answer I posted in:

Accept numeric input only

numeros = []

while True:
    try:
        numero = int(input("Informe um número inteiro positivo: "))
        if numero < 0:
            raise ValueError("O número deve ser inteiro positivo ou zero.")
        elif numero == 0:
            break
        else:
            numeros.append(numero)
    except ValueError as e:
        print("Valor inválido:", e)

And, to check if the list of numbers is in ascending order:

ordenado = numeros == sorted(numeros)

Finally, to get the size of the list, the native function len :

tamanho = len(numeros)

So getting:

numeros = []

while True:
    try:
        numero = int(input("Informe um número inteiro positivo: "))
        if numero < 0:
            raise ValueError("O número deve ser inteiro positivo ou zero.")
        elif numero == 0:
            break
        else:
            numeros.append(numero)
    except ValueError as e:
        print("Valor inválido:", e)

ordenado = numeros == sorted(numeros)
tamanho = len(numeros)

print(f'sim {tamanho}' if ordenado else f'não {tamanho}')

See working at Repl.it

    
04.04.2018 / 14:55