Chapter 20 – Frequency Analysis 311
Python’s sort() function can do this sorting for us if we pass it a function or method for its
key keyword argument. Normally the sort() function simply sorts the list it is called on into
alphabetical (or numeric) order. However, we can change this by passing the find() method of
the ETAOIN string as the key keyword argument. This will sort the items in the
freqToLetter[freq] list by the integer returned from the ETAOIN.find() method, that
is, the order that they appear in the ETAOIN string.
Normally the sort() method sorts the values in a list in ascending order (that is, lowest to
highest or the letter A first and letter Z last). If we pass True for the sort() method’s
reverse keyword argument, it will sort the items in descending order instead. The reason we
want to sort the letters in reverse ETAOIN order is so that ties result in lower match scores in the
englishFreqMatchScore() function rather than higher match scores. (This function is
explained later.)
If we continue using our “Alan Mathison Turing...” example value for freqToLetter, then
after the loop finishes the value stored in freqToLetter would be: {1: 'Z', 2: 'QJ', 3:
'X', 135: 'A', 8: 'K', 139: 'I', 140: 'T', 14: 'V', 21: 'Y', 30: 'BW', 36:
'P', 37: 'FU', 39: 'G', 58: 'MD', 62: 'L', 196: 'E', 74: 'C', 87: 'H', 89:
'S', 106: 'R', 113: 'O', 122: 'N'}
Notice that the strings for the 30 , 37 , and 58 keys are all sorted in reverse ETAOIN order.
Passing Functions as Values
freqAnalysis.py
48. freqToLetter[freq].sort(key=ETAOIN.find, reverse=True)
If you look on line 47 , you’ll notice that we are not calling the find() method but instead using
the find method itself as a value that is passed to the sort() method call. In Python, functions
themselves are values just like any other values. For example, try typing this into the interactive
shell:
def foo():
... print('Hello!')
...
bar = foo
bar()
Hello!
In the above code, we define a function named foo() that prints out the string 'Hello!'. But
this is basically defining a function and then storing it in a variable named foo. Then we copy