my cryptogram program

John Salerno johnjsal at NOSPAMgmail.com
Mon May 15 22:13:00 CEST 2006


Alrighty, here is what I've come up with. Any suggestions for tweaks or 
speed-boosting efficiency? Just kidding. :)

Maybe the weakest part is how the code is determined (just shuffling the 
letters in the alphabet). Perhaps there's a better way? Although it 
seems effective to me....


import string
import random
import itertools

def convert_quote(quote):
     coded_quote = make_code(quote)
     author = coded_quote.split('|')[1]
     quote = coded_quote.split('|')[0]
     return quote, author

def make_code(original):
     original_letters = make_set(original)
     new_letters = list(string.ascii_uppercase)
     while True:
         random.shuffle(new_letters)
         trans_letters = ''.join(new_letters)[:len(original_letters)]
         if test_code(original_letters, trans_letters):
             trans_table = string.maketrans(original_letters, trans_letters)
             break
     return original.translate(trans_table)

def make_set(original):
     original_set = set(original)
     punc_space = string.punctuation + string.whitespace
     for char in punc_space:
         if char in original_set:
             original_set.remove(char)
     return ''.join(original_set)

def test_code(original_letters, trans_letters):
     for pair in itertools.izip(original_letters, trans_letters):
         if pair[0] == pair[1]:
             return False
     return True

if __name__ == '__main__':
     print convert_quote("The past is not dead. In fact, it's not even 
past.|William Faulkner")



More information about the Python-list mailing list