TheRIProgrammer
TheRIProgrammer

Reputation: 87

Python 2: Sorting algorithm does not work

I am working on a program that takes a list and sorts it from highest to lowest [Yes I know I could use .sort()]. The program is the following:

UnList = raw_input("Enter a list of numbers seperated by commas") #collects the users list
List = UnList.split(",") #Turns the users numbers into a list
for x in range(len(List)): #number of time to sort
  Switcher = 0 #the switcher (also will reset it later)
  for z in range(len(List)-1): #number of time the switcher runs
    if List[Switcher] > List[(Switcher + 1)]: #if one number is bigger than the other
      List[Switcher],List[(Switcher+1)] = List[(Switcher+1)],List[Switcher] #this switches those 2 numbers
    Switcher += 1 #adds to the switcher
print "The new list is:", List #prints the output

Sometimes it works, as in with the example "1,7,4,6,3" Other times, such as with "-10,5,4,32,4,-40,2" it gives the completely incorrect output "['-10', '-40', '2', '32', '4', '4', '5']"

Upvotes: 1

Views: 86

Answers (3)

Mahendra Gaur
Mahendra Gaur

Reputation: 390

You are getting wrong output because you are using a list of string and not a list of integers. Convert your list of string to list of integers before processing the list.

Upvotes: 1

StephenTG
StephenTG

Reputation: 2647

Based on the order you're getting, I think the issue may be that the sort is going in lexicographic order, rather than numeric order. Ensure that all the elements are being compared as integers rather than strings

As Johny suggests, List = [int(x) for x in UnList.split(",")] would be one way to convert to a list of integers

Upvotes: 5

Alex
Alex

Reputation: 21766

You need to convert your values to integers, otherwise they do not get sorted correctly. You could do this by modifying the line of code that splits the strings:

List = map(int,UnList.split(",")) #Turns the users numbers into a list

After this change, the output is:

[-40, -10, 2, 2, 3, 4, 4, 5]

This is my full code:

UnList = '-10, -40, 2, 2, 3, 4, 4, 5'
List = map(int,UnList.split(",")) #Turns the users numbers into a list

for x in range(len(List)): #number of time to sort
  Switcher = 0 #the switcher (also will reset it later)
  for z in range(len(List)-1): #number of time the switcher runs
    if List[Switcher] > List[(Switcher + 1)]: #if one number is bigger than the other
      List[Switcher],List[(Switcher+1)] = List[(Switcher+1)],List[Switcher] #this switches those 2 numbers
    Switcher += 1 #adds to the switcher
print "The new list is:", List #prints the output

Upvotes: 2

Related Questions