Created
June 8, 2011 06:53
-
-
Save Jach/1013923 to your computer and use it in GitHub Desktop.
Caesar, ROT13 encryption/decryption
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 collections | |
import string | |
def rotate(lst, amount): | |
items = collections.deque(lst) | |
items.rotate(amount) | |
return items | |
def rotate_str(str, amount): | |
return ''.join(rotate(str, amount)) | |
def rotate_str_set(amount): | |
from_set = string.ascii_letters | |
to_set = rotate_str(string.ascii_lowercase, amount) + \ | |
rotate_str(string.ascii_uppercase, amount) | |
return from_set, to_set | |
def caes_set(): | |
return rotate_str_set(-3) | |
def rot13_set(): | |
return rotate_str_set(-13) | |
def caesar_table(): | |
return string.maketrans(*caes_set()) | |
def reverse_caesar_table(): | |
return string.maketrans(*caes_set()[::-1]) | |
def rot13_table(): | |
return string.maketrans(*rot13_set()) | |
def reverse_rot13_table(): | |
return string.maketrans(*rot13_set()[::-1]) | |
def translate(msg, table): | |
return msg.translate(table) | |
def test(tests, norm, rev): | |
for test in tests: | |
print translate(test[0], norm) == test[1],\ | |
translate(test[1], rev) == test[0] | |
assert translate(test[0], norm) == test[1] and\ | |
translate(test[1], rev) == test[0] | |
if __name__ == '__main__': | |
tests_caes = [ | |
('TIME WAITS FOR NO MAN', 'WLPH ZDLWV IRU QR PDQ'), | |
('Hello World', 'Khoor Zruog'), | |
] | |
tests_rot = [ | |
('A good morning to you', 'N tbbq zbeavat gb lbh'), | |
('What is for dinner', 'Jung vf sbe qvaare'), | |
] | |
cae_tab = caesar_table() | |
rev_cae = reverse_caesar_table() | |
rot_tab = rot13_table() | |
rev_rot = reverse_rot13_table() | |
try: | |
test(tests_caes, cae_tab, rev_cae) | |
test(tests_rot, rot_tab, rev_rot) | |
except AssertionError: | |
print 'Test failed!' | |
else: | |
print 'Tests succeeded.' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment