[Tutor] Script won't run for no apparent reason
Martin A. Brown
martin at linux-ip.net
Sat Aug 11 00:10:23 CEST 2012
Hello,
: #!/usr/bin/env python3
:
: import random
: values = {'a':'d', 'b':'e', 'c':'f', 'd':'g', 'e':'h', 'f':'i', 'g':'j',
: 'h':'k', 'i':'l', 'j':'m', 'k':'n', 'l':'o', 'm':'p', 'n':'q', 'o':'r',
: 'p':'s', 'q':'t', 'r':'u', 's':'v', 't':'w', 'u':'x', 'v':'y', 'w':'z',
: 'x':'a', 'y':'b', 'z':'c', 'A':'D', 'B':'E', 'C':'F', 'D':'G', 'E':'H',
: 'F':'I', 'G':'J', 'H':'K', 'I':'L', 'J':'M', 'K':'N', 'L':'O', 'M':'P',
: 'N':'Q', 'O':'R', 'P':'S', 'Q':'T', 'R':'U', 'S':'V', 'T':'W', 'U':'X',
: 'V':'Y', 'W':'Z', 'X':'A', 'Y':'B', 'Z':'C'}
This sort of thing always catches my eye, and I think to myself....
'Are there any tools or libraries in this language that I could use
to generate this, instead of writing out this repetitive data
structure?'
Here's what I did for my own amusement and possibly of benefit to
you. There are probably better solutions out there for your Caesar
cipher enjoyment, but I hope you may find this helpful.
# -- This code should create a dictionary that should look like the
# one above, but you can create it on the fly with a different
# value for the shift. You could also use a different alphabet.
#
def generate_caesar_cipher(alphabet,shift):
offset = shift - len(alphabet)
cipheralpha = ''.join((alphabet[offset:], alphabet[0:offset]))
return dict(zip(alphabet,cipheralpha))
caesar_shift = 3
values = dict()
values.update(generate_caesar_cipher(string.ascii_letters,caesar_shift))
One other thing to consider is that you can use the underutilized
function 'translate' from the string module. The 'maketrans'
function creates a translation table and the 'translate' function
applies that to input.
def alt_trans(plain_alpha,shift):
offset = shift - len(plain_alpha)
cipher_alpha = ''.join((plain_alpha[offset:], plain_alpha[0:offset]))
return string.maketrans(plain_alpha,cipher_alpha)
plaintext = 'Alea iacta est.'
shift_cipher = alt_trans(string.ascii_letters, caesar_shift)
ciphertext = string.translate(plaintext,shift_cipher)
Enjoy Python!
-Martin
--
Martin A. Brown
http://linux-ip.net/
More information about the Tutor
mailing list