CMU Coding Bootcamp
1from string import ascii_lowercase, ascii_uppercase
2
3
4def encodeSubstitutionCipher(msg: str, key: str) -> str:
5 """Encode a message using a substitution cipher."""
6 unique = set(msg)
7 for c in unique:
8 if c.isalpha():
9 if c.isupper():
10 encoded = key[ord(c) - ord("A")]
11 else:
12 encoded = key[ord(c) - ord("a")]
13 encoded = encoded.lower()
14 msg = msg.replace(c, encoded)
15 return msg
16
17
18def decodeSubstitutionCipher(encodedMsg: str, key: str) -> str:
19 """Decode a message using a substitution cipher."""
20 unique = set(encodedMsg)
21 for c in unique:
22 if c.isalpha():
23 if c.isupper():
24 decoded = ascii_uppercase[key.index(c.upper())]
25 else:
26 decoded = ascii_lowercase[key.index(c.upper())]
27 encodedMsg = encodedMsg.replace(c, decoded)
28 return encodedMsg
29
30
31print("Testing encodeSubstitutionCipher()...", end="")
32assert encodeSubstitutionCipher("CAB", "SQGYFEZXLANKJIMPURDCWTHVOB") == "GSQ"
33assert encodeSubstitutionCipher("Cab Z?", "SQGYFEZXLANKJIMPURDCWTHVOB") == "Gsq B?"
34assert (
35 encodeSubstitutionCipher("Hello, World!", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
36 == "Hello, World!"
37)
38assert (
39 encodeSubstitutionCipher("42 - 0 = 42", "XHNSBMTOPQWGZDCEAVLKJYIURF")
40 == "42 - 0 = 42"
41)
42assert encodeSubstitutionCipher("", "XHNSBMTOPQWGZDCEAVLKJYIURF") == ""
43
44
45print("Testing decodeSubstitutionCipher()...", end="")
46assert decodeSubstitutionCipher("GSQ", "SQGYFEZXLANKJIMPURDCWTHVOB") == "CAB"
47assert decodeSubstitutionCipher("Gsq B?", "SQGYFEZXLANKJIMPURDCWTHVOB") == "Cab Z?"
48assert (
49 decodeSubstitutionCipher("Hello, World!", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
50 == "Hello, World!"
51)
52assert (
53 decodeSubstitutionCipher("42 - 0 = 42", "XHNSBMTOPQWGZDCEAVLKJYIURF")
54 == "42 - 0 = 42"
55)
56assert decodeSubstitutionCipher("", "XHNSBMTOPQWGZDCEAVLKJYIURF") == ""
57print("Passed!")