Created
November 8, 2012 00:02
-
-
Save saltavenger/4035501 to your computer and use it in GitHub Desktop.
crypt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
def buildCoder(shift): | |
""" | |
Returns a dict that can apply a Caesar cipher to a letter. | |
The cipher is defined by the shift value. Ignores non-letter characters | |
like punctuation, numbers, and spaces. | |
shift: 0 <= int < 26 | |
returns: dict | |
""" | |
alpha = string.ascii_uppercase + string.ascii_lowercase | |
coder = {} | |
steps = shift | |
shift2 = shift + 26 | |
steps2 = shift | |
for c in alpha[0:26]: | |
if shift == 26: | |
shift = shift-steps | |
coder[c] = alpha[shift] | |
shift += 1 | |
else: | |
coder[c] = alpha[shift] | |
shift += 1 | |
steps += 1 | |
for c in alpha[26:52]: | |
if shift2 == 52: | |
shift2 = shift2-steps2 | |
coder[c] = alpha[shift2] | |
shift2 += 1 | |
else: | |
coder[c] = alpha[shift2] | |
shift2 += 1 | |
steps2 += 1 | |
return coder | |
import string | |
def applyCoder(text, coder): | |
""" | |
Applies the coder to the text. Returns the encoded text. | |
text: string | |
coder: dict with mappings of characters to shifted characters | |
returns: text after mapping coder chars to original text | |
""" | |
newText = '' | |
noList = string.punctuation + ' ' + '0123456789' | |
for c in text: | |
if c in noList: | |
newText += c | |
else: | |
newText += coder.get(c) | |
return newText | |
import string | |
def applyShift(text, shift): | |
""" | |
Given a text, returns a new text Caesar shifted by the given shift | |
offset. Lower case letters should remain lower case, upper case | |
letters should remain upper case, and all other punctuation should | |
stay as it is. | |
text: string to apply the shift to | |
shift: amount to shift the text (0 <= int < 26) | |
returns: text after being shifted by specified amount. | |
""" | |
return applyCoder(text, buildCoder(shift)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment