Chapter 18 – Hacking the Simple Substitution Cipher 259
Line 19’s for loop will loop through each character in the word parameter, assigning each
character to a variable named letter.
Line 20 checks if letter has not been seen before by checking that letter does not exist as a
key in the letterNums dictionary. (On the first iteration of the loop, the condition on line 20
will always be True because letterNums will be a blank dictionary that doesn’t have
anything in it.)
If we have not seen this letter before, line 21 adds this letter as the key and the string form of
nextNum as the key’s value to the letterNums dictionary. For the next new letter we find we
want to use the next integer after the one currently in nextNum anymore, so line 2 2 increments
the integer in nextNum by 1.
makeWordPatterns.py
23. wordPattern.append(letterNums[letter])
On line 23, letterNums[letter] evaluates to the integer used for the letter in the letter
variable, so this is appended to the end of wordPattern. The letterNums dictionary is
guaranteed to have letter for a key, because if it hadn’t, then lines 20 to 22 would have
handled adding it to letterNums before line 23.
makeWordPatterns.py
24. return '.'.join(wordPattern)
After the for loop on line 19 is finished looping, the wordPattern list will contain all the
strings of the complete word pattern. Our word patterns have periods separating the integers, so
that we could tell the difference between “1.12” and “11.2”. To put these periods in between each
of the strings in the wordPattern list, line 24 calls the join() method on the string '.'.
This will evaluate to a string such as '0.1.2.2.3.3.4'. The completely-built string that
join() returns will be the return value of getWordPattern().
The Word Pattern Program’s main() Function
makeWordPatterns.py
27. def main():
28. allPatterns = {}
The value stored in allPatterns is what we will write to the wordPatterns.py file. It is a
dictionary whose keys are strings of word patterns (such as '0.1.2.3.0.4.5' or