0
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!

4
  • 5
    That code won't generate that output. Please always copy and paste transcripts exactly, rather than write what you guess it should do. Commented Jan 29, 2015 at 21:40
  • @DSM -- I'm always amazed at how quickly you pick up on small nuances like OP forgot to bind the return value of sorted. You're a machine sir! Commented Jan 29, 2015 at 21:42
  • 1
    Lexicographic order is not the same as integer order. Commented Jan 29, 2015 at 21:42
  • @DSM -- Sorry. Im new to this stackoverflow thing! I repasted it exactly how I have it but I changed the sorted() to list.sort(). It still does not do what I want though. Any clue why? Commented Jan 29, 2015 at 21:47

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.