Reputation: 3
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.
Upvotes: 0
Views: 134
Reputation: 5986
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.
Upvotes: 1
Reputation: 1106
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!
Upvotes: 0
Reputation: 46
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
Upvotes: 0
Reputation: 5070
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]):
Upvotes: 1