|
| 1 | +""" |
| 2 | +Program to encode and decode Baconian or Bacon's Cipher |
| 3 | +Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher |
| 4 | +""" |
| 5 | + |
| 6 | +encode_dict = { |
| 7 | + "a": "AAAAA", |
| 8 | + "b": "AAAAB", |
| 9 | + "c": "AAABA", |
| 10 | + "d": "AAABB", |
| 11 | + "e": "AABAA", |
| 12 | + "f": "AABAB", |
| 13 | + "g": "AABBA", |
| 14 | + "h": "AABBB", |
| 15 | + "i": "ABAAA", |
| 16 | + "j": "BBBAA", |
| 17 | + "k": "ABAAB", |
| 18 | + "l": "ABABA", |
| 19 | + "m": "ABABB", |
| 20 | + "n": "ABBAA", |
| 21 | + "o": "ABBAB", |
| 22 | + "p": "ABBBA", |
| 23 | + "q": "ABBBB", |
| 24 | + "r": "BAAAA", |
| 25 | + "s": "BAAAB", |
| 26 | + "t": "BAABA", |
| 27 | + "u": "BAABB", |
| 28 | + "v": "BBBAB", |
| 29 | + "w": "BABAA", |
| 30 | + "x": "BABAB", |
| 31 | + "y": "BABBA", |
| 32 | + "z": "BABBB", |
| 33 | + " ": " ", |
| 34 | +} |
| 35 | + |
| 36 | + |
| 37 | +decode_dict = {value: key for key, value in encode_dict.items()} |
| 38 | + |
| 39 | + |
| 40 | +def encode(word: str) -> str: |
| 41 | + """ |
| 42 | + Encodes to Baconian cipher |
| 43 | +
|
| 44 | + >>> encode("hello") |
| 45 | + 'AABBBAABAAABABAABABAABBAB' |
| 46 | + >>> encode("hello world") |
| 47 | + 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' |
| 48 | + >>> encode("hello world!") |
| 49 | + Traceback (most recent call last): |
| 50 | + ... |
| 51 | + Exception: encode() accepts only letters of the alphabet and spaces |
| 52 | + """ |
| 53 | + encoded = "" |
| 54 | + for letter in word.lower(): |
| 55 | + if letter.isalpha() or letter == " ": |
| 56 | + encoded += encode_dict[letter] |
| 57 | + else: |
| 58 | + raise Exception("encode() accepts only letters of the alphabet and spaces") |
| 59 | + return encoded |
| 60 | + |
| 61 | + |
| 62 | +def decode(coded: str) -> str: |
| 63 | + """ |
| 64 | + Decodes from Baconian cipher |
| 65 | +
|
| 66 | + >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") |
| 67 | + 'hello world' |
| 68 | + >>> decode("AABBBAABAAABABAABABAABBAB") |
| 69 | + 'hello' |
| 70 | + >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") |
| 71 | + Traceback (most recent call last): |
| 72 | + ... |
| 73 | + Exception: decode() accepts only 'A', 'B' and spaces |
| 74 | + """ |
| 75 | + if set(coded) - {"A", "B", " "} != set(): |
| 76 | + raise Exception("decode() accepts only 'A', 'B' and spaces") |
| 77 | + decoded = "" |
| 78 | + for word in coded.split(): |
| 79 | + while len(word) != 0: |
| 80 | + decoded += decode_dict[word[:5]] |
| 81 | + word = word[5:] |
| 82 | + decoded += " " |
| 83 | + return decoded.strip() |
| 84 | + |
| 85 | + |
| 86 | +if "__name__" == "__main__": |
| 87 | + from doctest import testmod |
| 88 | + |
| 89 | + testmod() |
0 commit comments