How would you solve this simple question?

Asked

Viewed 86 times

1

I was solving a simple Python question

The program asks for three numbers and returns in descending order -

I decided to do it using a list, like this:

numeros = []
for i in range(0,3):
    numeros.append(int(input('Digite um numero: : ')))
    numeros.sort()
    numeros.reverse()

print('a ordem eh:',numeros)

The program worked, but I was wondering if this resolution is 'accepted' in the eyes of an experienced programmer. And if not, how would they do?

2 answers

4


You don’t need to sort the list with each data entry, you can do this only at the end, because the methods sort and reverse work with all data from the list:

numeros = []

for i in range(0,3):
    numeros.append(int(input('Digite um numero: : ')))

numeros.sort()
numeros.reverse()

print('a ordem eh:',numeros)

See online: https://repl.it/repls/DependableDopeyDecompiler


It is also possible to sort the list with only one line, using the parameter reverse of the method sort:

numeros = []

for i in range(0,3):
    numeros.append(int(input('Digite um numero: : ')))

numeros.sort(reverse=True)

print('a ordem eh:',numeros)

See online: https://repl.it/repls/SwelteringAttractiveAttribute


If you only need to display the sorted list, you could also use the function sorted, which, unlike the methods used, receives a list and does not change it, it returns a new ordered list:

numeros = []

for i in range(0,3):
    numeros.append(int(input('Digite um numero: : ')))

print('a ordem eh:',sorted(numeros, reverse=True))

See online: https://repl.it/repls/VitalFrightenedApplicationsoftware

  • Thank you! You helped a lot

0

There is a more succinct way to resolve this issue, using only 2 lines of code. For this we will need to use the functions Sorted, list and map.

The script would be mounted this way:

numeros = sorted(list(map(int, input('Digite todos os valores: ').split())), reverse=True)
print(f'\033[32ma ordem eh: {numeros}')

Note that when we run this script we receive the following message: Digite todos os valores:. Right now we must type all the values of the list in the same line, separated for a single space and press enter.

From this moment on the algorithm will capture all the entered values, assemble a list in descending order, and then display the list in descending order.

Browser other questions tagged

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