I am new to Python. First, the code is supposed to take an input (in the form of "x/y/z" where x,y, and z are any positive integer) and split it into three different variables.
input = raw_input()
a, b, c = input.split("/", 2)
I want the second part of my code to take these three variables and sort them based on their numerical value.
order = [a, b, c]
print order
order.sort()
print order
While this works perfectly for most inputs, I have found that for inputs "23/9/2" and "43/8/2" the output has not been sorted so is not returned in the correct order. Any thoughts as to what could be causing inputs such as these to not work?
The issue is that you are sorting strings, and expecting them to be sorted like integers. First convert your list of strings to a list of ints if you would like numerical sorting.
>>> sorted(['23', '9', '2'])
['2', '23', '9']
>>> sorted(map(int, ['23', '9', '2']))
[2, 9, 23]
Here is how you could rewrite your code:
input = raw_input()
a, b, c = map(int, input.split("/", 2))
order = [a, b, c]
print order
order.sort()
print order
If you need to convert them back to strings, just use map(str, order). Note that on Python 2.x map() returns a list and on 3.x it will return a generator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With