Make a Program that reads three numbers and shows them in descending order. Python

Asked

Viewed 7,986 times

-1

Hello, I’m trying to make an algorithm that reads three numbers in Python and delivers them in descending form. The code is right, but I know you can write better only using logic...

a = float(input('Escreva um número: '))
b = float(input('Escreva um número: '))
c = float(input('Escreva um número: '))

if a >= b and a >= c and b >= c:
    print(f'A ordem decrescente é {a} , {b} e {c}')
elif a >= b and a >=c and c >= b:
    print(f'A ordem decrescente é {a} , {c} e {b}')
elif b >= a and b >= c and a >= c:
    print(f'A ordem decrescente é {b} , {a} e {c}')
elif b >= a and b >= c and c >= a:
    print(f'A ordem decrescente é {b} , {c} e {a}')
elif c >= a and c >= b and a >=b:
    print(f'A ordem decrescente é {c} , {a} e {b}')
elif c >= a and c >= b and b >= a:
    print(f'A ordem decrescente é {c} , {b} e {a}')

I wrote this algorithm based on this:

prod_1 = float(input('Valor 1° produto: '))
prod_2 = float(input('Valor 2° produto: '))
prod_3 = float(input('Valor 3° produto: '))

if prod_1 <= prod_2 and prod_1 <= prod_3:
    print('Compre o primeiro produto.')
elif prod_2 <= prod_3:
    print('Compre o segundo produto.')
else:
    print('Compre o terceiro produto')

So I don’t think you need to use lists and something more elaborate, it would just be to exercise logic.

But I don’t think it’s possible to do it without writing a lot of code for a weird task.

2 answers

2

Hello, a different way to solve is by using listas and for.

follows an example:

lista = []
qtd = 3
for i in range(qtd):
    elemento = int(input('Digite um numero: '))
    lista.append(elemento)

lista.sort(reverse = True) //ordena os elementos
print(lista)

2

In general, for any number of elements, the simplest is to place the elements in a list and sort them, as suggested by another answer.

But in the specific case of 3 numbers, and without using lists, you can do so:

if a < c:
    a, c = c, a

if a < b:
    a, b = b, a

if b < c:
    b, c = c, b

print(f'A ordem decrescente é {a}, {b} e {c}')

The first if checks whether a is less than c, and if it is, change their values (a takes on the value of c, and c takes on the value of a). That is, after this if, I know that a will surely be greater or equal to c.

Then I do the same with b, and after the second if I’m sure that a is greater than or equal to b. And as the first if assured that a is greater than or equal to c, so at this point I already know that a is the greatest of all.

Then all that remains is to check whether b is less than c, and if so, I change their values. So, after the third if, for sure b shall be greater than or equal to c.

So at the end of these three if's, I know that a, b and c will be in unbelieving order.

Browser other questions tagged

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