Editor

Ranks with Ties

Advanced · Stretch · from Python Sorting: sort(), sorted(), Key Functions, and Custom Order

From the lesson: Python Sorting: sort(), sorted(), Key Functions, and Custom Order

Imagine your bookshelf at home. Books are scattered everywhere - some by title, some by color, some shoved in sideways. Finding anything takes forever.

Read the lesson

Write a function rank_players(scores) that takes a list of (name, score) tuples and returns a list of (rank, name) tuples for a results table:

  • The highest score comes first. Players with the same score are listed in alphabetical order and share a rank.
  • After a tie, the next rank skips the places the tie used: 1, 2, 2, 4.
  • rank_players([("ann", 90), ("bob", 95), ("cy", 90), ("dee", 80)])
    # [(1, 'bob'), (2, 'ann'), (2, 'cy'), (4, 'dee')]

    Return the answer instead of printing it: Check calls rank_players() with its own scores, some of them hidden.

    def rank_players(scores):
    pass
    Solution unlocks after your first Check

    What Check runs

    Your code runs first, then each of these lines, and 4 more that stay hidden. The output must match exactly.

    RunsExpected output
    rank_players([("ann", 70), ("bob", 95), ("cy", 80)])[(1, 'bob'), (2, 'cy'), (3, 'ann')]
    rank_players([("max", 50), ("lea", 50)])[(1, 'lea'), (1, 'max')]

    More Sorting exercises

    All Python exercises · 50 practice problems · Data Structures quiz