308 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
The getLetterCount() function returns a dictionary value where the keys are single
uppercase letter strings, and the values are an integer showing how many times that letter occurs
in the message parameter. For example, a certain string value for the message parameter with
135 A’s, 30 B’s, and so on will cause getLetterCount() to return {'A': 135, 'B': 30,
'C': 74, 'D': 58, 'E': 196, 'F': 37, 'G': 39, 'H': 87, 'I': 139, 'J': 2,
'K': 8, 'L': 62, 'M': 58, 'N': 122, 'O': 113, 'P': 36, 'Q': 2, 'R': 106,
'S': 89, 'T': 140, 'U': 37, 'V': 14, 'W': 30, 'X': 3, 'Y': 21, 'Z': 1}
Line 1 6 starts the letterCount variable with a dictionary that has all keys with a value of 0.
freqAnalysis.py
18. for letter in message.upper():
19. if letter in LETTERS:
20. letterCount[letter] += 1
The for loop on line 18 iterates through each character in the uppercase version of message.
On line 19 , if the character exists in the LETTERS string, we know it is an uppercase letter. In
that case line 2 0 will increment the value at letterCount[letter].
freqAnalysis.py
22. return letterCount
After the for loop on line 18 finishes, the letterCount dictionary will have a count of how
often each letter appeared in message. This dictionary is returned from getLetterCount().
The Program’s getItemAtIndexZero() Function
freqAnalysis.py
25. def getItemAtIndexZero(x):
26. return x[0]
The getItemAtIndexZero() function is very simple: it is passed a tuple and returns the
items at index 1. This function will be passed as the key keyword argument for the sort()
method. (The reason for this will be explained later.)
The Program’s getFrequencyOrder() Function
freqAnalysis.py
29. def getFrequencyOrder(message):
30. # Returns a string of the alphabet letters arranged in order of most