Least to greatest
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?
numbers = (55, -55, 5, -5, 0.005, -0.005, 0) print(sorted(numbers))
When I try this
It gives me this, input is 5, 6,7,4
[' ', ' ', ' ', ',', ',', ',', '4', '5', '6', '7']
strwhich is iterable.
sortedtakes an iterable, and returns a sorted list.
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
splitit, 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
which safely evaluates the input as a python expression, so a comma separated sequence becomes a tuple that can then be sorted.
Thanks @JonB, this helped a lot!
print(sorted(input().replace(',', ' ').split()))
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.