Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When my code sorts the inputs, why doesn't it work in certain scenarios?

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?

like image 791
zch Avatar asked Nov 29 '25 02:11

zch


1 Answers

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.

like image 187
Andrew Clark Avatar answered Nov 30 '25 15:11

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!