high scores table
A simple implementation of a high scores table in Python.
# This is a two dimensional list of names and scores.
# This list is not in order.
scores = [['john',56],
['alan',12],
['joyce',9],
['betty',99],
['gary',45],
['bob',56],
['frank',113]]
# Let's print out the scores as they are.
# It's not pretty but it shows us the structure.
print('Original scores table')
for score in scores:
print(score)
# This is the insertion sort from CS18 Sorting and Searching
# I've changed the sequence variable to scores and used
# item[1] to use the score as the sort 'column' from the list.
# I've also changed the direction of the sort by altering
# the '>' to a '<' on the line with the comment.
for i in range(1, len(scores)):
item = scores[i]
current = i - 1
placed = False
while (current >= 0) and not placed:
if scores[current][1] < item[1]: # Sort using the score, high to low
scores[current + 1] = scores[current]
current = current - 1
else:
placed = True
scores[current + 1] = item
# We can now truncate the scores table to leave the top 5 scores
highscores = scores[:5]
# Now print them out. You could do whatever you wanted with this
# list like saving them in a file for instance.
print('\nTop 5 scores')
for highscore in highscores:
print(highscore)
Last modified: February 26th, 2022