Created
August 13, 2012 23:35
-
-
Save dvoiss/3344842 to your computer and use it in GitHub Desktop.
Reddit Daily Programmer Challenge: Vigenère cipher
This file contains hidden or 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
#!/usr/bin/python | |
# For the reddit daily programmer challenge | |
# Challenge: http://www.reddit.com/r/dailyprogrammer/comments/y5sox/8132012_challenge_88_easy_vigen%C3%A8re_cipher/ | |
# Solution: http://www.reddit.com/r/dailyprogrammer/comments/y5sox/8132012_challenge_88_easy_vigen%C3%A8re_cipher/c5socop | |
# by @dvoiss on github / @daveasaurus on reddit | |
from string import ascii_uppercase as up | |
def encode(text, cipher, decode=False): | |
result, cipher_index, decode = '', 0, -1 if decode else 1 | |
for i, x in enumerate(text): | |
result += up[(up.index(x) + (decode * up.index(cipher[cipher_index % len(cipher) ]))) % 26] | |
cipher_index += 1 | |
return result | |
print encode("THECAKEISALIE", "GLADOS", False) # ZSEFOCKTSDZAK | |
print encode("ZSEFOCKTSDZAK", "GLADOS", True) # THECAKEISALIE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment