Skip to content
Hello Python

Checking your account…

Sign in to save your code and progress across devices. The lesson and problem statement remain public.

Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace

Problem

Implement top_words(counts, limit). Return up to limit words ordered by descending count, breaking ties alphabetically.

Starter code

def top_words(counts, limit):
    pass
Test cases

sample

{
  "args": [
    {
      "beta": 2,
      "alpha": 2,
      "gamma": 1
    },
    2
  ]
}

Expected: ["alpha","beta"]

Wizard outline
  1. Step 1: Encode frequency and tie ordering

    Order every word by descending count and then alphabetically. A tuple key makes the primary and tie-break rules explicit in one deterministic ordering.

  2. Step 2: Return only the requested prefix

    Return at most limit ranked words. Slicing naturally handles zero and limits larger than the number of words.

Footguns and prerequisites
  • Alphabetical sorting alone ignores the primary frequency rank.
  • functions
Reviewed references
Prepared Interview Problems
Recommended approach and implementation

Sort keys by a compound negative-count and word key.

Why it works: The key establishes descending frequency first and lexical order for every tie.

def _rank_words(counts):
    return sorted(counts, key=lambda word: (-counts[word], word))

def top_words(counts, limit):
    return _rank_words(counts)[:limit]
Similar exercises