Sign in to run and submit your work
Reading is open to everyone. Running code and saving drafts need an account so your work is yours and comes back on your next visit.
or
CODE WORKSPACE
A leaderboard is regenerated every hour, and people notice when rows swap places for no reason. They swap because several rows share the top amount and nothing in the sort decides which of them comes first.
Write rank_rows(rows, limit). It ranks by amount descending, then region ascending, then id ascending, and returns the ids of the top limit rows.
Function to write
rank_rows(rows: list[dict], limit: int | None) -> list[str]A list of row ids in ranked order, truncated to `limit` when one was given.
How to approach it
Sort the tied rows twice from two different input orders and compare.
Sample cases
+ 2 held back until you submit
a three-way tie, top three
Three rows share an amount, so region then id decides the order — not arrival order.
Input
Argument 1
| id | amount | region |
|---|---|---|
| c | 120 | eu |
| a | 120 | eu |
| b | 90 | us |
| d | 120 | ap |
Argument 2
3Returns
[
'd',
'a',
'c'
]no limit
`None` means the whole ranking, which is not the same as a limit of zero.
Input
Argument 1
| id | amount | region |
|---|---|---|
| c | 120 | eu |
| a | 120 | eu |
| b | 90 | us |
| d | 120 | ap |
Argument 2
None
Returns
[
'd',
'a',
'c',
'b'
]no rows
An empty input ranks to an empty list rather than raising on the slice.
Input
Argument 1
[] (empty list)
Argument 2
3Returns
[] (empty list)
Constraints
limit of None means return the whole ranking.limit of 0 returns an empty list. It is a real limit, not an absent one.Worked example
Rows a, c and d all have an amount of 120, in regions eu, eu and ap. Ranked, the top three are d, a, c — ap sorts before eu, and between the two eu rows the id decides.
The starter sorts on amount alone, so those three come back in whatever order they arrived in. That is stable in the sense Python means, and not stable in the sense a reader means: change the upstream read order and the leaderboard changes with it.
What this tests
That a sort key is a tuple, that mixing directions is done by negating a component rather than by reversing the whole sort, and that a tie-break is a correctness rule rather than a nicety when anything downstream pages or diffs the result.
rank_rows(rows: list[dict], limit: int | None) -> list[str]Submit for review to find out what your query gets right, what it gets wrong, and how it compares with the best working query for this exercise.
This scenario runs a full workspace — editor, canvas and results side by side. It needs a laptop or desktop to be usable. Open this page on a bigger screen to start building.