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