The Score Sorter
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Players tied on points are listed alphabetically by name, so the standings never depend on who was entered first. An analyst rebuilding a tournament leaderboard from players, a list of [name, score] pairs, needs those standings with the highest scores at the top.
Points on the board, sorted by who earned the most.
Example
Input:
players = [["Carol",95],["Bob",87],["Alice",95],["Dave",70]]
Output:
[["Alice",95],["Carol",95],["Bob",87],["Dave",70]]
Worked solution and explanation
Two directions, one ordering
This is a two-key ordering where the keys disagree on direction: score runs high to low, name runs A to Z. Everyone gets the score part right. The question is what happens at a tie. Sort on score alone and Carol stays ahead of Alice because she was entered first. Reach for reverse=True on a (score, name) key and the names flip to Z->A. Either way the tied players land in an order the leaderboard can't defend.
Step 1: Read the tie in the example
The visible case has Carol and Alice both on 95, with Carol entered first. The expected output puts Alice first. That one pair tells you entry order does not survive and that names go A to Z within a score.
Step 2: Make score descend without touching name
Python compares tuples left to right, so a key of (-score, name) puts higher scores first because their negation is smaller, and leaves name ascending. One key, one pass, both directions correct.
Step 3: Return a new list
sorted builds a fresh list and leaves players untouched, and an empty input simply returns [].
def sort_scores(players):
sorted_players = sorted(players, key=lambda p: (-p[1], p[0]))
return sorted_players-p[1] carries the descending direction; p[0] stays ascending.
def sort_scores(players):
return sorted(players, key=lambda p: (p[1], p[0]), reverse=True)Returns Carol before Alice: reverse=True reverses the name too.
- Negated key
sorted(players, key=lambda p: (-p[1], p[0]))handles both directions in one sort. Works because scores are numbers you can negate.- Two stable passes
- Sort by
p[0]first, then byp[1]withreverse=True. Python's sort is stable, so names stay A to Z inside each score. Same result, and the move you need when the descending key is a string.
Common follow-up questions
- What if the descending key were a string, so you couldn't negate it? (Tests the two-pass stable sort or `functools.cmp_to_key`.)
- What if you only needed the top 10 players? (Tests `heapq.nsmallest` with the same `(-score, name)` key.)
- How would you write this in SQL? (Tests `ORDER BY score DESC, name ASC`.)