Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 255

Sample Run of the Word Pattern Module


Running this program doesn’t print anything out to the screen. Instead it silently creates a file
named wordPatterns.py in the same folder as makeWordPatterns.py. Open this file in IDLE’s file
editor, and you will see it looks like this:


allPatterns = {'0.0.1': ['EEL'],
'0.0.1.2': ['EELS', 'OOZE'],
'0.0.1.2.0': ['EERIE'],
'0.0.1.2.3': ['AARON', 'LLOYD', 'OOZED'],
...the rest has been cut for brevity...


The makeWordPatterns.py program creates wordPatterns.py. Our Python program creates a
Python program! The entire wordPatterns.py program is just one (very big) assignment statement
for a variable named allPatterns. Even though this assignment statement stretches over
many lines in the file, it is considered one “line of code” because Python knows that if a line ends
with a comma but it is currently in the middle of a dictionary value, it ignores the indentation of
the next line and just considers it part of the previous line. (This is a rare exception for Python’s
significant indentation rules.)


The allPatterns variable contains a dictionary value where the keys are all the word patterns
made from the English words in the dictionary file. The keys’ values are lists of strings of English
words with that pattern. When wordPatterns.py is imported as a module, our program will be able
to look up all the English words for any given word pattern.


After running the makeWordPatterns.py program to create the wordPatterns.py file, try typing the
following into the interactive shell:





import wordPatterns
wordPatterns.allPatterns['0.1.2.1.1.3.4']
['BAZAARS', 'BESEECH', 'REDEEMS', 'STUTTER']


wordPatterns.allPatterns['0.1.2.2.3.2.4.1.5.5']
['CANNONBALL']


wordPatterns.allPatterns['0.1.0.1.0.1']
Traceback (most recent call last):
File "", line 1, in
KeyError: '0.1.0.1.0.1'


'0.1.0.1.0.1' in wordPatterns.allPatterns
False




Free download pdf