On Fri, Aug 10, 2012 at 6:10 PM, Martin A. Brown <mar...@linux-ip.net> wrote: > > : 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))
Close, but you're rotating the lower and uppercase letters together. In the original they're separate. Here's a different approach using itertools: from itertools import islice, cycle from string import ascii_lowercase, ascii_uppercase def make_caesar_cipher(alphabet=ascii_lowercase, shift=3): return dict(zip(alphabet, islice(cycle(alphabet), shift, None))) values = make_caesar_cipher() values.update(make_caesar_cipher(ascii_uppercase)) _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor