e3c183d06a4017f0bb504de54c1f053178b56cae
[cipher-training.git] / cipher.py
1 import string
2
3 def caesar_encipher_letter(letter, shift):
4 """Encipher a letter, given a shift amount
5
6 >>> caesar_encipher_letter('a', 1)
7 'b'
8 >>> caesar_encipher_letter('a', 2)
9 'c'
10 >>> caesar_encipher_letter('b', 2)
11 'd'
12 >>> caesar_encipher_letter('x', 2)
13 'z'
14 >>> caesar_encipher_letter('y', 2)
15 'a'
16 >>> caesar_encipher_letter('z', 2)
17 'b'
18 >>> caesar_encipher_letter('z', -1)
19 'y'
20 >>> caesar_encipher_letter('a', -1)
21 'z'
22 """
23 if letter in string.ascii_letters:
24 if letter in string.ascii_uppercase:
25 alphabet_start = ord('A')
26 else:
27 alphabet_start = ord('a')
28 return chr(((ord(letter) - alphabet_start + shift) % 26) +
29 alphabet_start)
30 else:
31 return letter
32
33 def caesar_decipher_letter(letter, shift):
34 """Decipher a letter, given a shift amount
35
36 >>> caesar_decipher_letter('b', 1)
37 'a'
38 >>> caesar_decipher_letter('b', 2)
39 'z'
40 """
41 return caesar_encipher_letter(letter, -shift)
42
43 def caesar_encipher(message, shift):
44 """Encipher a message with the Caesar cipher of given shift
45
46 >>> caesar_encipher('abc', 1)
47 'bcd'
48 >>> caesar_encipher('abc', 2)
49 'cde'
50 >>> caesar_encipher('abcxyz', 2)
51 'cdezab'
52 >>> caesar_encipher('ab cx yz', 2)
53 'cd ez ab'
54 """
55 enciphered = [caesar_encipher_letter(l, shift) for l in message]
56 return ''.join(enciphered)
57
58 def caesar_decipher(message, shift):
59 """Decipher a message with the Caesar cipher of given shift
60
61 >>> caesar_decipher('bcd', 1)
62 'abc'
63 >>> caesar_decipher('cde', 2)
64 'abc'
65 >>> caesar_decipher('cd ez ab', 2)
66 'ab cx yz'
67 """
68 return caesar_encipher(message, -shift)
69
70
71 if __name__ == "__main__":
72 import doctest
73 doctest.testmod()