Last active
March 13, 2019 12:34
-
-
Save AvverbioPronome/4a56a944e5ee409122b2e7b531f70399 to your computer and use it in GitHub Desktop.
Caesar
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/env python3 | |
from string import ascii_uppercase | |
alphabeth = ascii_uppercase | |
def caesar(string, key): | |
"""Given a `string` and a `key`, return-s a string in which every | |
character is substituted with the one `key` positions forward in | |
the `alphabeth`. | |
Function `c` is analogous to chr(), and function `o` to its | |
opposite, ord(). | |
I am thinking of writing this function without relying on the | |
"expensive" .find() method, we should use a dictionary where | |
cipher-char is the key, and translated is the value, so that we | |
can translate with translated = translator[cipher-char]. | |
""" | |
import functools | |
o = lambda l: alphabeth.find(l) | |
c = lambda n: alphabeth[n % len(alphabeth)] | |
lettershift = lambda n, l: c(o(l)+n) if l in alphabeth else l | |
return ''.join(map(functools.partial(lettershift, key), string)) | |
def caesar2(string, key): | |
d = {k: v for k, v in zip(alphabeth, alphabeth[key:] + alphabeth[:key])} | |
return ''.join(map(lambda l: d[l] if l in d.keys() else l, string)) | |
def main(): | |
import sys | |
try: | |
f = open(sys.argv[1]) | |
except: | |
f = sys.stdin | |
text = ''.join(f) | |
for i in range(len(alphabeth)): | |
for line in text.splitlines(): | |
print ("{}".format(i).zfill(2), ': ', | |
caesar(line.upper(), i), sep='') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment