Goal: to use the dictionary data structure in Python.
Make sure to complete Lab 12 before doing the homework.
Create a Python script file called hw12.py. Add your name at the top as a comment, along with the class name and date.
When people are texting, they use shortcuts for faster typing. Consider the following list of shortcuts:
Text | Shortcut |
at | @ |
and | & |
one, won | 1 |
to, too, two | 2 |
for, four, fore | 4 |
be, bee, bea | b |
sea, see | c |
eye | i |
are | r |
you | u |
why | y |
For example, the sentence "see you before class" can be written as "c u b4 class".
To encode a text using these shortcuts, we need to perform a replace of the text on the left with the text on the right. However, for sequences that are part of each other, such as "be" and "bee", the longer one should be replaced first. We'll assume that the text is provided in all lowercase letters.
a. Write a function encode(text) that takes in a parameter representing a text to encode, and returns the encoded text based on the table above.
For this purpose, create a dictionary in the function that contains all the entries on the left of the table as keys and the shortcut we the associated value. Write the words with the same shortcut in reverse order of the length, from the longest to the shortest.
After that, use a for loop that goes over all the items in the
dictionary. For each of them, call the function replace from the text
with the key and the value, and store the result back in the variable
text:
text = text.replace(key, value)
After the loop, return the variable text.
b. Write a main function where you ask the user for a text to encode, input it, and store it in a variable. Then call the function encode with this variable and output the result.
Make a call to the function main somewhere after it.
Write a function decode(text) that takes a string that has some encoded words in it, and writes it back in clear text. Use the same dictionary as in the first exercise. You can also use the function searchValue that we wrote in Lab 11. This time, we are searching for whole words in the text that may be found as values in the dictionary. We don't want to replace substrings of words, because the results may not be what we want.
So use the function text.split() to split the text into words and store it in a variable words. Then for each word, check if the function searchValue returns a key that is not None. If it is, then assign to that element of the words list, the key that was returned. If not, leave that word unchanged. At the end, use the function ' '.join(words) to assemble the full text back and return it.
Add a test to this function in the main and then output the result. If we start from a text, and use first the encode, and then the decode functions, will the result always be the same as the original text?
Upload the files lab12.py and hw12.py in Canvas, Assignments, Homework 12.