Skip to content

Instantly share code, notes, and snippets.

@inky
Created August 2, 2015 11:01
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 inky/eb4f673973829c881afe to your computer and use it in GitHub Desktop.
Save inky/eb4f673973829c881afe to your computer and use it in GitHub Desktop.
Caesar cipher
#!/usr/bin/env python3
import argparse
import string
import sys
def rotate(letters, offset):
return letters[offset:] + letters[:offset]
def cipher(message, map_dict):
return ''.join(map_dict.get(c, c) for c in message)
class CaesarCipher:
def __init__(self, offset):
lower, upper = string.ascii_lowercase, string.ascii_uppercase
offset = offset % len(lower)
plain = lower + upper
rotated = rotate(lower, offset) + rotate(upper, offset)
pairs = tuple(zip(plain, rotated))
self._encipher = {x: y for (x, y) in pairs}
self._decipher = {y: x for (x, y) in pairs}
def encipher(self, message):
return cipher(message, self._encipher)
def decipher(self, message):
return cipher(message, self._decipher)
def main():
parser = argparse.ArgumentParser(
description="Encipher or decipher text from standard input.")
parser.add_argument('-r', '--rotate', type=int)
parser.add_argument('-d', '--decipher', action='store_true')
args = parser.parse_args()
if not args.rotate:
parser.print_help()
return
caesar = CaesarCipher(args.rotate)
action = caesar.decipher if args.decipher else caesar.encipher
message = sys.stdin.read()
sys.stdout.write(action(message))
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment