Problem 59

completed January 30, 2012

Comments

I had to do this problem in three steps.

First, I learned how to read and write to files finally. That should have happened ages ago. It was helpful because I needed to decipher the text like 17 thousand times.

The second step was to then dig through all of the text till I found the one that was deciphered correctly. I opened the file in Safari, because that seemed to be the only one that wouldn’t crash. I then used the ‘find’ function to look for the text ‘ the ‘ because I figured that was common enough to be in whatever text was given. Doing that made it really easy to find the correct decipher key.

The last step was to then take the deciphered text and add up the value of the ASCII codes for each character.

If I could do this problem again, I would add in a search for ‘ the ‘ before writing the text to the file. This way, only a very small number of deciphers would be printed.

Below is the code for the first and last steps.

Code

from itertools import *
from operator import xor
from string import ascii_lowercase

cipherFile = open('cipher1.txt', 'r')
decipherFile = open('decipher.txt', 'w')

for key in product(ascii_lowercase, repeat=3):
	
	for n in cipherFile:
		fixedFile = n.split(',')

	iikey = []
	for l in key:
		iikey.append(ord(l)) 
	
	decipherFile.write(str(key))
	for decode in izip(cycle(iikey), map(int, fixedFile)):
		decipherFile.write(chr(xor(decode[0], decode[1])))
	
decipherFile.close()


total = 0
with open('59.decipher.txt', 'r') as d:
	for w in d:
		for c in w:
			total += ord(c)

print total