Skip to content

Instantly share code, notes, and snippets.

@CasperCL
Last active February 19, 2019 20:38
Show Gist options
  • Save CasperCL/eb5c85d4c4a91f9f9d05f355f4383d18 to your computer and use it in GitHub Desktop.
Save CasperCL/eb5c85d4c4a91f9f9d05f355f4383d18 to your computer and use it in GitHub Desktop.
Caesar Cipher
"""
Simple implementation of the Caesar cipher that works for the English alphabet
"""
alphabet = [chr(letter) for letter in range(97, 123)]
def caesar_cipher(text, key):
"""
Enciphers/deciphers a text.
@param text: to encipher/decipher
@param key: use a positive number to encipher and a negative to decipher
"""
text_ = ""
for c in text:
text_ += shift(c.lower(), key)
return text_
def shift(char, n):
""" Shifts a letter by `n` letters and wraps at z to a."""
try:
index = alphabet.index(char)
except ValueError:
return char # unknown letter
index += n
if index > 25: index = index - 26
return alphabet[index]
text = "Hello, my name is CasperCL"
code = caesar_cipher(text, 13)
deciphered = caesar_cipher(code, -13)
assert text.lower() == deciphered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment