Codiqo

Learn Python · lesson 56 of 60 · about 10 minutes

Project: Leaderboard

Read game scores and turn them into a ranked, filtered leaderboard.

What you'll learn

  • Parse name-score lines into pairs
  • Rank players with sorted and a key
  • Summarise results with comprehensions

Games night

Sam and friends have a games night, and the assistant keeps the leaderboard. Each score is typed as a name and points, like Ada 340, until done, and a line that doesn't fit gets a reminder. The reading is already written for you: it leaves a list of (name, points) pairs called scores. Your part is the leaderboard: rank the scores, number the top three and list the 300 club, everyone on 300 points or more.

The plan

Each line of input is a name and a score, like Ada 340. The leaderboard program will:

1. Turn the lines into (name, score) pairs
2. Sort them by score, highest first
3. Print the top three with their places
4. List everyone who scored at least 300

Step 1: lines into pairs

lines = ["Ada 340", "Bo 510", "Cy 120"]
pairs = [(line.split()[0], int(line.split()[1])) for line in lines]
print(pairs)

Output

[('Ada', 340), ('Bo', 510), ('Cy', 120)]

Ranking and numbering

sorted(pairs, key=lambda p: p[1], reverse=True) ranks the players. enumerate(..., start=1) numbers them from 1, and slicing [:3] keeps only the top three.

Steps 2 to 4

pairs = [("Ada", 340), ("Bo", 510), ("Cy", 120), ("Dee", 300)]
ranked = sorted(pairs, key=lambda p: p[1], reverse=True)
for place, (name, score) in enumerate(ranked[:3], start=1):
    print(f"{place}. {name} {score}")
print([name for name, score in ranked if score >= 300])

Output

1. Bo 510
2. Ada 340
3. Dee 300
['Bo', 'Ada', 'Dee']

Ties and short lists

Two players on the same points stay in the order they were typed, even with reverse=True, so the earlier score ranks higher. And ranked[:3] never goes wrong: with only one player it simply gives a list of one, so the loop prints one line.

Tip

for place, (name, score) in ... unpacks each numbered pair in one go. The brackets around name, score matter: each item is a number plus a pair.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.