Example Application: Text
Composed of a dictionary and message. Common sequences of characters (may be handled as, i.e., words) are replaced with dictionary references.
Implementation
class EncodedMessage:
def __init__(self, message: str, dictionary: list[str]):
self.message = message
self.dictionary = dictionary
def __str__(self):
return self.message
def perform_encoding(string: str) -> EncodedMessage:
words = string.split(" ")
# Tally the frequency of each word
dict_words = {}
for word in words:
if word in dict_words and not word.isnumeric():
dict_words[word] += 1
else:
dict_words[word] = 1
# Form a dictionary of repeating words
repeating_words = [word for word in dict_words if dict_words[word] > 1]
repeating_words_dict = { # Used to quickly find the index of a word rather than searching through the list
word: index for index, word in enumerate(repeating_words)
}
# Encode the words
encoded_string = ""
for word in words:
if word in repeating_words:
encoded_string += f"{repeating_words_dict[word]} "
else:
encoded_string += f"{word} "
return EncodedMessage(encoded_string[:-1], repeating_words)
def perform_decoding(encoded_message: EncodedMessage) -> str:
words = encoded_message.message.split(" ")
decoded_message = ""
for word in words:
if word.isnumeric():
decoded_message += f"{encoded_message.dictionary[int(word)]} "
else:
decoded_message += f"{word} "
return decoded_message[:-1]
message = (
"ask not what your country can do for you but what you can do for your country"
)
encoded_message = perform_encoding(message)
decoded_message = perform_decoding(encoded_message)
print(f"Encoded message: {encoded_message}")
print(f"Decoded message: {decoded_message}")
print(f"Passed test? {message == decoded_message}")
Example
ask not what your country can do for you but what you can do for your country