0
import csv names = [] scores = [] length = 0 with open('table.csv') as csvfile: read = csv.reader(csvfile, delimiter = ',') for row in read: name = row[0] score = row[1] length = length + 1 names.append(name) scores.append(score) print(names) print(scores) #printing unsorted list #using bubble sort done = 0 while done != 1: done = 1 for i in range(length - 1): if scores[i] > scores[i +1]: scores[i],scores[i+1] = scores[i + 1], scores[i] names[i],names[i+1] = names[i + 1], names[i] done = 0 print("") print(names) print(scores) 

Click here to access image that shows the output of the code

This code is meant to print out the high score table for a game that I'm developing. I know using bubble sort is very inefficient but I'm just trying it out for now. So basically the problem with the code is that it orders them, but if the number is bigger than 100,000 it seems to skip over the last zero and put it in order as if it was 10000 I'm thinking something may either be wrong with the number of loops or maybe over 100000 would usually be written as 100,000 messing with the csv file, I honestly don't know though.

2
  • 1
    for any 2 values which are in correct order at the end of for loop, your code will exit(because done will be equal to 1) Commented Oct 17, 2017 at 9:49
  • Your ordering strings so it's alphabetically, the results seem coherent. Commented Oct 17, 2017 at 9:50

4 Answers 4

1

The problem is that when reading the csv file, you get strings. Then, the bubble sort is doing lexicographical sorting and not the numerical sort you are looking for.

To fix it typecast the score into int (assuming the scores are integers) as follows

score = int(row[1]) 

and then it should work properly.

Sign up to request clarification or add additional context in comments.

Comments

1

In if statement you compares strings, not int. Try to replace

if scores[i] > scores[i +1]:

with

if int(scores[i]) > int(scores[i +1]):

Comments

0

The numbers are being stored as strings which is causing your sort to see all the 1's as the first rather than their integer value

Comments

0

I think it's because they are being treated at string values and not number (e.g. ints). Therefore the comparison is being done on the first character which in the case of 100,000 is "1". For example, by this logic 55,000 is greater than 100,000 as 5 is greater than 1.

Hope this helps, let me know how it goes!

1 Comment

Going a lot better, producing the right output now, thanks!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.