Counter

Counter

Counter, from the collections module, counts things. Give it a list (or a string) and it returns a dictionary-like object mapping each value to how many times it occurs:

from collections import Counter

votes = ["red", "blue", "red", "red", "green"]
counts = Counter(votes)
print(counts)
print(counts["red"])

Output:

Counter({'red': 3, 'blue': 1, 'green': 1})
3

Unlike a plain dictionary, a missing key is not an error — it counts as 0: counts["purple"] is 0.

most_common(n) returns the n highest counts as a list of (value, count) tuples:

print(counts.most_common(1))

Output:

[('red', 3)]

This replaces the manual counting-dictionary pattern from the dictionaries section — same result, one line.

Exercise

  1. Import Counter from collections.
  2. Define a function named letter_counts with one parameter, word. It returns a Counter of the characters in word.
  3. Define a function named most_frequent_letter with one parameter, word (non-empty). It returns the single most common character.

most_frequent_letter("banana") returns "a".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestCounter(unittest.TestCase):
    def test_letter_counts_of_banana(self):
        counts = letter_counts("banana")
        self.assertEqual(counts["a"], 3)
        self.assertEqual(counts["n"], 2)
        self.assertEqual(counts["b"], 1)

    def test_missing_letter_counts_as_zero(self):
        self.assertEqual(letter_counts("banana")["z"], 0)

    def test_most_frequent_letter_of_banana(self):
        self.assertEqual(most_frequent_letter("banana"), "a")

    def test_most_frequent_letter_of_zzzap(self):
        self.assertEqual(most_frequent_letter("zzzap"), "z")
from collections import Counter


def letter_counts(word):
    return Counter(word)


def most_frequent_letter(word):
    return letter_counts(word).most_common(1)[0][0]


print(letter_counts("banana"))
print(most_frequent_letter("banana"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.