felicia_rae
felicia_rae

Reputation: 23

Sorting negative integer strings in python

def sort_int_string(this_string):
    split_str = this_string.split()
    split_str.sort()
    join_str = ' '.join(split_str)
    return join_str

>>>print(sort_int_string("4 1 -1 -3"))
-1 -3 1 4

This code is meant to produce the proper order of "-3 -1" but for some reason I am getting this output where positive numbers are correct but the negatives are not. Any insight on what I am doing wrong? Thanks!

Upvotes: 0

Views: 2165

Answers (2)

dawg
dawg

Reputation: 104072

You can use a regex:

>>> import re
>>> sorted(re.findall(r'-?\d+', "4 1 -1 -3"), key=int)
['-3', '-1', '1', '4']

That produces the strings in sorted order by their value.

You can rejoin into a string:

>>> sor=sorted(re.findall(r'-?\d+', "4 1 -1 -3"), key=int)
>>> ' '.join(sor)
'-3 -1 1 4'

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124090

You are sorting strings, not numbers, and those are sorted lexicographically; like words in a dictionary. - happens to be sorted before digits, but '1' is still sorted before '3'. Furthermore, '10' sorts before '2' because '1' comes before '2' in a character table.

Sort numerically by converting each element to an integer while sorting:

split_str.sort(key=int)

Demo, with your corrected function:

>>> def sort_int_string(this_string):
...     split_str = this_string.split()
...     split_str.sort(key=int)
...     join_str = ' '.join(split_str)
...     return join_str
... 
>>> print(sort_int_string("4 1 -1 -3"))
-3 -1 1 4

Upvotes: 2

Related Questions