Your first problem is that you have inconsistent indentation. On a few lines you're using tabs instead of spaces, which is a very bad idea. Indentation is significant in Python, so it is easy to make errors if you don't watch out.
The second problem that I think you're having is that you're comparing strings, rather than numbers. Python is perfectly happy to sort strings, but it will use lexicographical orering, which can be unexpected when applied to integers encoded as strings. For example, the string "11"
will be sorted ahead of the string "2"
, since it's first character 1
comes before 2
in the ASCII character set (and also in Unicode).
As I asked in a comment, it's not clear how you're determining that your code isn't working correctly. It may be that simply fixing the issues I described above will fix the problems you're having. If they do not, please explain how you're determining that your results are invalid and I'll try to update this post with further suggestions.