Code

Count the Signal Letters

Code-breakers have another clue: some letters are much more common than others. In English, e shows up far more than z. If the most common letter in a secret is h, maybe h stands for e! This is called frequency analysis.

To count letters, use a dictionary as a tally sheet. Each letter is a key and its count is the value:

counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)   # {'b': 1, 'a': 3, 'n': 2}

counts.get(ch, 0) means "the count so far, or 0 if this letter is new".

Python also has a ready-made tally tool. Counter from the collections module does the same counting in one line: Counter("banana"). It's great to know, but write the loop yourself here so you see how it works.

Assignment

  1. count_letters(text) returns a dict of lowercase letters and their counts. Count A and a as the same letter. Skip anything that is not a letter (spaces, digits, punctuation).
  2. top_letter(text) returns the most common letter. It must use count_letters. If there is a tie, return the letter that comes first in the alphabet.