forked from exercism/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
44 lines (31 loc) · 1.2 KB
/
example.py
File metadata and controls
44 lines (31 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from string import ascii_lowercase
from time import time
import random
class Cipher:
def __init__(self, k=None):
if k:
self.key = _normalize(k)
else:
random.seed(time())
self.key = ''.join(random.choice(ascii_lowercase)
for i in range(100))
def base_encode(self, s, shift):
xkey = self.key * (len(s) // len(self.key) + 1)
return ''.join(shift(c, k) for c, k in zip(s, xkey))
def encode(self, s):
s = _normalize(s)
shift = lambda c, k: chr(((ord(c) + ord(k) - 2 * ord('a'))
% len(ascii_lowercase)) + ord('a'))
return self.base_encode(s, shift)
def decode(self, s):
shift = lambda c, k: chr(((ord(c) - ord(k) + len(ascii_lowercase))
% len(ascii_lowercase)) + ord('a'))
return self.base_encode(s, shift)
class Caesar(Cipher):
def __init__(self):
Cipher.__init__(self, 'd')
def _normalize(s):
return ''.join([c for c in s if c.isalpha()]).lower()
if __name__ == '__main__':
print(Caesar().encode('venividivici'))
print(Caesar().encode('\'Twas the night before Christmas'))