Python list of positive and negative numbers

Asked

Viewed 1,661 times

0

How do I make the user type positive and negative numbers in the same row and the list display them in order from the smallest to the largest, preferably not using loop?

Exemplo de números digitados
[1, 2, 3, 4, 5, -1, -2, -3, -4, -5]

Exemplo de como a saída deve ser:
[-5, -4, -3, -2, -1, 1, 2, 3, 4, 5] 

1 answer

3

With the method sort(). Example:

lista = []
i = 0
while i < 6:
    lista.append(int(input()))
    i += 1
lista.sort()
print(lista)

To reverse the order just do:

lista.sort(reverse = True)

without the while:

lista = []
lista.append(int(input()))
lista.append(int(input()))
lista.append(int(input()))
lista.append(int(input()))
lista.sort()
print(lista)

insert all items at once:

lista = input().split()
lista.sort()
print(lista)

In the latter case the list will be of the type pq string the split() method can only be used in strings, but if you need it to be of another type, just convert later. Remembering that values should be separated by spaces.

  • For the user to enter the positive and negative numbers randomly where the list should organize them from the largest pro minor, the example I did was to output the code

  • truth, lack of attention my kkkkk, but the Sort() method will sort anyway.

  • edited the answer

  • How does that code look without using loop? (for teaching purposes and understanding)

  • the difference is that you would have to put a list.append(int(input())) for each item you want to add to the list

  • How do you insert all the codes on the same line?

  • I edited in response, to better see

  • why are there so many list.append(int(input()))?

  • was just to illustrate that you need one for each item you want to add (in the example you asked to use looping)

  • 1

    Alex says, as Laís explained, this is perfect, but it would be illogical to do this operation without loop. Because then it would be a very bad code to write, unless it is a requirement not to use any kind of loop, which for me would not make sense since it makes our life as a programmer much easier.

  • 1

    @Laísgodinho, you could do it lista = [ int(a) for a in input().split() ] if I’m not mistaken. Then you have, again, the whole to play with

  • lista = input().split()&#xA;lista.sort()&#xA;print(lista) It’s strange she shows the results like this: ['-2', '-3', '-3', '-6', '1', '3', '4', '5'], negative numbers are not in order like positive numbers

Show 7 more comments

Browser other questions tagged

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