...

/

Solution Review: Decode the Message

Solution Review: Decode the Message

The solution to the 'Decode the Message' challenge.

We'll cover the following...
Press + to interact
Python 3.10.4
def decode(func):
def wrapper(message):
# Sorting the message after being cleaned
message = sorted(func(message))
for index in range(0, len(message)):
n = 0-(int(message[index])-9) # Mapping numbers to their actual values
message[index] = str(n)
s = ""
return s.join(message)
return wrapper
@decode
def clean_message(message):
# Removing every character that's not digit
cleaned = [character for character in message if character.isdigit()]
return cleaned
print(clean_message('323 23jdfd9 1323'))

Explanation

In the code above, according to the problem statement, there are two parts: the clean _message function and the decode decorator. Let us first go through the clean_message function.

Look at the header of the function at line 13. It takes the message as a parameter. The purpose of the function is to remove all the characters that are not digits. The string is an immutable type, so to alter the message, we’ll use the list for the modification. At line 15, using list comprehension, we filter out every character that is not a digit (using an isdigit() function). The filtered message is then returned.

What about the other two tasks: sorting and mapping? For these, we have the decode decorator. Look at its definition at line 1. It takes a function (that needs to be decorated) as a parameter. Then, we have a wrapper inside that carries the message as a parameter, just like the clean_message function. We call the func function. On decorating clean_message with decode, this will call clean_message. Then, we are sorting the result using sorted() function.

Look at line 6. Here, we are only mapping the digits to actual values by subtracting 9, and then removing the negative sign. The updated value is then placed at its index. That’s not it. We need a string as an output, but we have a list right now. So, we use the join function on an empty string to concatenate it with the list (see line 9) and return it.

Look at line 12. We decorate the clean_message function using @decode. At line 18, we call the function with 323 23jdfd9 1323, as a parameter which returns 8777666660 as a decoded message.


Ask