Forum Archive

Least to greatest

Evan03Davis

Hey, I am trying to make a program that you enter a bunch of numbers and it then returns all the numbers but in order least to greatest.
I haven't gotten anywhere but I was wondering how would you define the numbers least to greatest?

ccc
numbers = (55, -55, 5, -5, 0.005, -0.005, 0)
print(sorted(numbers))
Evan03Davis

When I try this

print(sorted(input()))

It gives me this, input is 5, 6,7,4

[' ', ' ', ' ', ',', ',', ',', '4', '5', '6', '7']
JonB

input() returns a str which is iterable.
sorted takes an iterable, and returns a sorted list.

So, sorted('bca') returns a list of the sorted characters, ['a', 'b', 'c'].

If you want to interpret the input as a list of some kind, you need to split it, perhaps using spaces or commas, depending on what you want your input format to be. i.e sorted(input().split(',')). of course, if you want to sort NUMBERS, you need to convert to a number before sorting, otheriwse 11 comes before 2.

sorted([int(x) for x in input().split(',')])

or maybe more robust

sorted(ast.literal_eval(input()))

which safely evaluates the input as a python expression, so a comma separated sequence becomes a tuple that can then be sorted.

Evan03Davis

Thanks @JonB, this helped a lot!

ccc

print(sorted(input().replace(',', ' ').split()))

JonB

ccc, try typing

1, 2, 3, 20, 111

and you will see the issue. your code (and my first similar attempt) sorts strings, not numbers. hence the literal_eval. int(split...) would also work, assuming the numbers are ints only, otherwise float(split...) would work similarly.