### High Scores Table

 If you ever need to create a 'top x' table or list (a high scores table for instance), this is the script that you need. It simple takes a two dimensional list of scores, runs them through an insertion sort and then truncates them to the top 5. The clever bit is that the sort is done on the second value in the sublist - the comments explain it all.`# 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)`
ċ
Mark Mills,
18 Apr 2020, 13:57