Exercise 5: Eliminate Duplicates
Replace duplicate words with their numbers.
We'll cover the following
Problem statement
This chapter explains how to use dictionaries for fast lookup of items (words, in our case). Keep a dictionary of the words that have been seen before, with their numbers as values. When adding a new word to the dictionary, assign the next number to it. Use the dictionary and formatted string to replace the known words with their numbers.
Task
Given text as a string, replace all duplicate occurrences of a word after the first with a unique number that represents that word, prefixed with the hash sign (#
).
Example
The input "I am Sam I am Sam Sam I am"
will become "I am Sam #0 #1 #2 #2 #0 #1"
.
Note: Assume that the
text
consists only of letters and spaces, with no punctuation.
Get hands-on with 1400+ tech skills courses.