
Jonathan S. answered 02/20/23
Experienced Math Educator and Former Google Software Engineer
def encrypt(msg):
"""
Encrypts the given message using the following rules:
- If the character is an uppercase: change it to lowercase with '!' sign on its both sides (e.g. 'M' --> '!m!');
- If the character is a lowercase: change it to uppercase with '!' sign on its both sides (e.g. 'm' --> '!M!');
- If the character is a digit: cube the digit, i.e. raise to the power of 3 (e.g. '5' --> '125');
- If the character is a blank space: replace it with '$' symbol;
- Otherwise: keep it as it is.
Args:
msg (str): The message to encrypt.
Returns:
str: The encrypted message.
"""
encrypted_msg = ""
for char in msg:
if char.isupper():
encrypted_msg += "!" + char.lower() + "!"
elif char.islower():
encrypted_msg += "!" + char.upper() + "!"
elif char.isdigit():
encrypted_msg += str(int(char) ** 3)
elif char.isspace():
encrypted_msg += "$"
else:
encrypted_msg += char
return encrypted_msg
# Unit tests
assert encrypt("Hello, World!") == "!hELLO, wORLD!"
assert encrypt("This is a Test") == "!tHIS$!iS$!a$!tEST"
assert encrypt("12345") == "1491625"
assert encrypt(" ") == "$$$$"
assert encrypt("}~Abc5") == "}~!aBC125"
assert encrypt("") == ""