Hacking Secret Ciphers with Python

(Ann) #1

310 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


to frequency values, the freqToLetter dictionary will map frequency keys to list of letter
values.


Line 38 creates a blank dictionary. Line 39 loops over all the letters in LETTERS. The if
statement on line 40 checks if the letter’s frequency (that is, letterToFreq[letter])
already exists as a key in freqToLetter. If not, then line 4 1 adds this key with a list of the
letter as the value. Or else, line 43 appends the letter to the end of the list that is already at
letterToFreq[letter].


If we continue to use our “Alan Mathison Turing...” example value of letterToFreq then
freqToLetter would end up looking like this: {1: ['Z'], 2: ['J', 'Q'], 3: ['X'],
135: ['A'], 8: ['K'], 139: ['I'], 140: ['T'], 14: ['V'], 21: ['Y'], 30:
['B', 'W'], 36: ['P'], 37: ['F', 'U'], 39: ['G'], 58: ['D', 'M'], 62:
['L'], 196: ['E'], 74: ['C'], 87: ['H'], 89: ['S'], 106: ['R'], 113:
['O'], 122: ['N']}


The sort() Method’s key and reverse Keyword Arguments


freqAnalysis.py
45. # third, put each list of letters in reverse "ETAOIN" order, and then
46. # convert it to a string
47. for freq in freqToLetter:
48. freqToLetter[freq].sort(key=ETAOIN.find, reverse=True)
49. freqToLetter[freq] = ''.join(freqToLetter[freq])


The third step of getFrequencyOrder() to is sort the letter strings in each list in
freqToLetter in reverse ETAOIN order (as opposed to alphabetical order).


Remember that freqToLetter[freq] will evaluate to a list of letters that have a frequency
count of freq. A list is used because it’s possible that two or more letters have the exact same
frequency count, in which case this list will have two-or-more-letters strings in it.


When multiple letters are tied for frequency, we want these tied letters to be sorted in the reverse
order that they appear in the ETAOIN string. We need this so that we have a consistent way of
breaking ties. Otherwise messages with the same letter frequencies might produce different return
values from getFrequencyOrder()!


For example, if E appears 15 times, D and W appear 8 times each, and H appears 4 times, we
would want them to be sorted as 'EWDH' and not 'EDWH'. This is because while E is the most
frequent, D and W have the same frequency count but W comes after D in the ETAOIN string.

Free download pdf