A Python program to solve a cipher

This section demonstrates how a Python program can be used to solve a cryptogram, in this case a monoalphabetic substitution cipher. (There is a similar section using javascript here). 

The ciphertext to be solved is:
OJNPZ FDWXJ UHDNI JGKFD QDPDQ JODHI XIFJK DSBZW NBQZH HBIZD VIDFF DHQIJ HSBQB JHHJF JHMDN NDLRB NDSUB ODEHJ UPDTD NXQAB HM

The plaintext solution is:

forsalebyownercompletesetofencyclopediabritannica
excellentconditionnolongerrequiredwifeknowseverything

using this Key:
Plaintext : abcdefghijklmnopqrstuvwxyz
Ciphertext: ZWISDOMABCEFGHJKLNPQRTUVXY


If you are not familiar with the Hillclimbing algorithm, you may want to first read this section

Python Program. You can download the Python program here. It runs in the latest version of Python (3.2.3) You will also need to download a table of log tetragram frequencies here to do the scoring. The program and table need to be placed in the same folder.

The program works like this:

1. load the table of log tetragraphs from the file "TetraLog_hank.doc"

2. remove the spaces from the ciphertext

3. make a random mixed alphabet and use it to decipher and score

4. swap every combintion of letters in the mixed alphabet, each time deciphering and scoring. Keep the mixed alphabet only if the score improves.

5. repeat (4) for as long as the score improves. Otherwise return to (3)