liveBook · Manning

Counter

As explained in Python Workout, Second Edition

Counter is a Python class in the collections module that maps hashable elements to their occurrence counts.

Use Counter from Python’s collections module when a problem asks how often hashable elements occur. It behaves like a dict while providing counting operations such as most_common. section 4.15 section 4.22

For each word, count its letters, select the highest count, then use max with a key function to choose the word whose repeated letter occurs most often. Calling most_common(1) returns one descending-ranked pair; [0][1] extracts its count. section 4.14 section 4.15

words = ['this', 'is', 'an', 'elementary', 'test', 'example']

Start with a small word sequence for the repeated-letter exercise. section 4.14

>>> Counter('abcabcabbbc').most_common()     #1
[('b', 5), ('a', 3), ('c', 3)]

Inspect the descending frequency pairs produced by most_common. section 4.15

def most_repeating_letter_count(word):
    return Counter(word).most_common(1)[0][1]

Encapsulate the indexed extraction in a helper, then pass that helper to max. section 4.15

def most_repeating_word(words):
    return max(words,
                   key=most_repeating_letter_count)

Select the word with the greatest repeated-letter count using max and a key function. section 4.15

How Python Workout, Second Edition covers it

How deep it goes
Explains dict inheritance, sequence initialization, most_common ranking, and indexed extraction, but omits broader Counter operations.
Examples
Uses letter frequencies in words, Counter output, most_common listings, and helper functions for selecting the winning word.
What it assumes
Assumes familiarity with Python functions, dict-like objects, sequences, indexing, max, and key functions.
What you can do after
Apply it via collections.Counter and most_common to count sequence elements and rank their frequencies.
How it connects
Connects Counter with dict, sequences, most_common, max, key functions, lists, and tuples.

Also explained in

Compare how 3 books explain Counter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.