Something went wrong. Try again.
CMU Coding Bootcamp
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from string import ascii_lowercase, ascii_uppercase
def encodeSubstitutionCipher(msg: str, key: str) -> str: """Encode a message using a substitution cipher.""" unique = set(msg) for c in unique: if c.isalpha(): if c.isupper(): encoded = key[ord(c) - ord("A")] else: encoded = key[ord(c) - ord("a")] encoded = encoded.lower() msg = msg.replace(c, encoded) return msg
def decodeSubstitutionCipher(encodedMsg: str, key: str) -> str: """Decode a message using a substitution cipher.""" unique = set(encodedMsg) for c in unique: if c.isalpha(): if c.isupper(): decoded = ascii_uppercase[key.index(c.upper())] else: decoded = ascii_lowercase[key.index(c.upper())] encodedMsg = encodedMsg.replace(c, decoded) return encodedMsg
print("Testing encodeSubstitutionCipher()...", end="")assert encodeSubstitutionCipher("CAB", "SQGYFEZXLANKJIMPURDCWTHVOB") == "GSQ"assert encodeSubstitutionCipher("Cab Z?", "SQGYFEZXLANKJIMPURDCWTHVOB") == "Gsq B?"assert ( encodeSubstitutionCipher("Hello, World!", "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == "Hello, World!")assert ( encodeSubstitutionCipher("42 - 0 = 42", "XHNSBMTOPQWGZDCEAVLKJYIURF") == "42 - 0 = 42")assert encodeSubstitutionCipher("", "XHNSBMTOPQWGZDCEAVLKJYIURF") == ""
print("Testing decodeSubstitutionCipher()...", end="")assert decodeSubstitutionCipher("GSQ", "SQGYFEZXLANKJIMPURDCWTHVOB") == "CAB"assert decodeSubstitutionCipher("Gsq B?", "SQGYFEZXLANKJIMPURDCWTHVOB") == "Cab Z?"assert ( decodeSubstitutionCipher("Hello, World!", "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == "Hello, World!")assert ( decodeSubstitutionCipher("42 - 0 = 42", "XHNSBMTOPQWGZDCEAVLKJYIURF") == "42 - 0 = 42")assert decodeSubstitutionCipher("", "XHNSBMTOPQWGZDCEAVLKJYIURF") == ""print("Passed!")