
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
count_letters(text)returns a dict of lowercase letters and their counts. CountAandaas the same letter. Skip anything that is not a letter (spaces, digits, punctuation).top_letter(text)returns the most common letter. It must usecount_letters. If there is a tie, return the letter that comes first in the alphabet.
count_letters(text)returns a dict of lowercase letters and their counts. CountAandaas the same letter. Skip anything that is not a letter (spaces, digits, punctuation).top_letter(text)returns the most common letter. It must usecount_letters. If there is a tie, return the letter that comes first in the alphabet.
main.py Python sleeping
Press Run to try your code, then Check to test it.