1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Counting with a dict

A dict finds a key without scanning, which makes it the natural tool for "how many of each?". The classic loop is:

counts = {}
for item in items:
    counts[item] = counts.get(item, 0) + 1

counts.get(item, 0) gives the current count, or 0 the first time an item shows up. collections.Counter(items) builds the same dict in one call.

Once you have counts, many questions become one more step: the biggest count is max(counts.values()), items seen more than once are the keys whose count is above 1, and the number of pairs inside a group of c equal items is c * (c - 1) // 2.

Counting once with a dict replaces "for every item, scan the whole list". That difference is what the speed tests check.

Watch the counts column in the table: one key grows by one on every pass.

See it run

words = ["tea", "jam", "tea", "bun", "tea"]
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)

A tally in a dict: each word becomes a key, its value is how often it appeared.

Practice counting with a dict

Exercise 1

You are sorting a pile of trading stickers. Each sticker is named by a string in stickers.

Return the number of copies of your most common sticker, as an integer.

Rules:

  • Names are case-sensitive: "Owl" and "owl" are different stickers.
  • An empty pile gives 0.

Constraints: 0 ≤ len(stickers) ≤ 10^5.

Example: solution(["owl", "fox", "owl"]) returns 2 because "owl" appears twice.

Exercise 2

A library scanner logs a card number every time a card is swiped. swipes is the list of card numbers in the order they were logged.

Return a list of the card numbers that were swiped more than once, sorted from smallest to largest, with each number listed once.

Rules:

  • If no card was swiped more than once, return [].
  • Card numbers can be zero or negative.

Constraints: 0 ≤ len(swipes) ≤ 10^5.

Example: solution([4, 7, 4, 9, 7, 4]) returns [4, 7] because 4 was swiped three times and 7 twice.

Exercise 3

A coat-check desk gives every coat a colour code. tags is the list of codes in the order the coats arrived. Two coats are twins when they sit at positions i < j and have the same code.

Return how many twin pairs there are, as an integer.

Rules:

  • Each pair of positions counts once, so three coats with the same code make 3 pairs.
  • Fewer than two coats gives 0.

Constraints: 0 ≤ len(tags) ≤ 8000; codes are integers.

Example: solution([1, 2, 1, 1]) returns 3: positions (0,2), (0,3) and (2,3).

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest