+ 1

Help appreciated to simplify code! Sort input numbers.

I coded a little program that receives input numbers from user and sorts them from low to high in a list. As it is, the program works all right but I had to include a few IFs to manage special cases I didn't know how to include in the main block... (e.g. when it is the first number in the list, or the highest/lowest yet to appear...) Any ideas very much appreciated! https://code.sololearn.com/chZ410PNhBRH/#py

2nd Dec 2018, 10:56 AM
Fernando Borreguero Blanco
Fernando Borreguero Blanco - avatar
5 Antworten
+ 1
Actually I didn't know there were built in sorting methods... I'm quite new to python! I'll investigate those but for now I would like to optimize my own sorting code! Many thanks
2nd Dec 2018, 11:08 AM
Fernando Borreguero Blanco
Fernando Borreguero Blanco - avatar
+ 1
If you want to insert each element in place at the moment it's given, keeping things simple, I would go with a for loop: for i in range(len(thatlist)): if n<thatlist[i]: thatlist.insert(i, n) break else: thatlist.append(n) The else part is outside of the for loop and will only be executed if there is no break.
2nd Dec 2018, 11:32 AM
HonFu
HonFu - avatar
+ 1
Your code works fine. Because the SoloLearn online compiler requires all inputs to be entered at once, they have to be on separate lines. Try this: 2 (enter) 4 (enter) 3 (enter) quit (submit) you should get [2, 3, 4] (otherwise you get an EOFError) You won't get that problem with, e. g. IDLE, VS Code or Pydroid3. See https://www.google.ca/search?q=sololearn+input+problem&oq=sololearn+input+problem&aqs=chrome..69i57j33.14884j0j4&sourceid=chrome-mobile&ie=UTF-8
2nd Dec 2018, 2:21 PM
David Ashton
David Ashton - avatar
0
Do you explicitly want to write your own sorting method instead of using the built-in ways?
2nd Dec 2018, 11:02 AM
HonFu
HonFu - avatar
0
Ok, many thanks for your help!
2nd Dec 2018, 4:09 PM
Fernando Borreguero Blanco
Fernando Borreguero Blanco - avatar