Skip to content

Instantly share code, notes, and snippets.

@dvoiss
Created August 13, 2012 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvoiss/3344842 to your computer and use it in GitHub Desktop.
Save dvoiss/3344842 to your computer and use it in GitHub Desktop.
Reddit Daily Programmer Challenge: Vigenère cipher
#!/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