Reputation: 1
I'm trying to write the scores to an external file and then view the top 5 scores sorted by the scores. This is my code:
def winner_1(total_score_1):
print(player_1 + " is the WINNER!")
Winner_1 = (str(total_score_1) + " points. Scored by " + player_1)
f = open("leaderboard.txt", "a")
f.write(''.join(Winner_1))
f.write('\n')
f.close()
# Subroutine if player 2 wins and to write the score and winners name to external file
def winner_2(total_score_2):
print(player_2 + " is the WINNER!")
Winner_2 = (str(total_score_2) + " points. Scored by " + player_2)
f = open("leaderboard.txt", "a")
f.write(''.join(Winner_2))
f.write('\n')
f.close()
if total_score_1 > total_score_2:
winner_1(total_score_1) #call in the subroutine that player 1 won
elif total_score_2 > total_score_1:
winner_2(total_score_2) #call in the subroutine that player 2 won
else:
tie(total_score_1, total_score_2)
scores = list()
with open('leaderboard.txt', 'r') as f:
for line in f: #reads in the scores from the file and add them to the list
scores.append(line.strip())
f.close()
#sorts the scores in reverese so the highest scores are at the top
scores.sort(reverse = True)
scores_top_5 = scores[0:5] #store the top 5 as a variable
#print the top 5 using a for loop so it shows as a list
i = 1
for x in scores_top_5:
print(i, ".", x) #it shows the position of the player in the leaderboard
i += 1
I'm trying to sort it so the highest scores come first so if anyone could help I'd really appreciate it.
Upvotes: 0
Views: 55
Reputation: 412
when you read lines from a file, your numbers are converted to strings, and that messes up your numeric sort (you don't want a lexical sort). you need to convert them back to numbers:
scores.append(int(line.strip()))
Upvotes: 0
Reputation: 8001
You post likely want to convert your scores to a int like this:
for line in f: #reads in the scores from the file and add them to the list
scores.append(int(line.strip()))
Note this will crash if scores exist that don't consist entirely of integers. You can also use float
instead if your scores include a decimal point.
If the data type is int
the scores will sort by value rather than lexicographically.
Alternatively, you can use the key in sort:
scores.sort(key=int, reverse=True)
This will not modify your array but sort them as expected. This will again crash if any numbers are not valid integers. Again you can substitute int with float for decimal points.
Upvotes: 1