Sort a leaderboard by score, then latency, then name with np.lexsort
Why it matters Multi-key sorting with explicit tie-breakers keeps leaderboards and ranked retrieval results stable and fair.
A model leaderboard sorts by score (higher first); ties go to the faster model (lower latency), and remaining ties to the alphabetically first name. np.lexsort does a multi-key sort in one call, but its key order trips people up.
Write leaderboard_order(scores, latency, names). All three are 1D arrays of length N (names are strings). Return the int array of indices that orders the leaderboard: score descending, then latency ascending, then name ascending.
def leaderboard_order(scores, latency, names)Example
scores [0.9, 0.8, 0.9], latency [120, 50, 80], names ['a', 'b', 'c'] gives [2, 0, 1].
Understand the idea
Sorting by several keys means: sort by the main key, and only use the next key when the main key ties. np.lexsort does this with a tuple of keys, but it reads them from the END: the last key is primary, the one before it breaks ties, and so on. It is stable, so full ties keep their input order.
Worked example: scores [0.9, 0.8, 0.9], latency [120, 50, 80]. Score descending puts items 0 and 2 (0.9) before item 1 (0.8). Items 0 and 2 tie, so latency decides: item 2 (80) before item 0 (120). Order [2, 0, 1].
Rule: np.lexsort((tie2, tie1, primary)). For descending numbers, use -key.
Leaderboards, ranked search results and deterministic top-k with tie-breaking use multi-key sorts.
Shapes and data flow
scores, latency, names (N,) -> order (N,)