Lesson 9
No Object is an Island
Chapter 4: More iterable objects
enumerate Exercise
Here’s a quick exercise to try to use enumerate
for yourself.
Write a function get_word_positions()
that takes a list
of str
as input. It should return a dict
where the keys are the unique set of strings in the input list
(i.e. the vocabulary), and the values are a list of indices where the word occurs in the list (starting from 0). See sample usage below.
While there are many ways to solve this problem, do use the enumerate
object since this is an exercise to practise that!
Sample usage
>>> words = ["feelings", "feelings", "like", "i've", "never", "lost", "you", "and", "feelings", "like", "i've", "never", "have", "you"]
>>> positions = get_word_positions(words)
>>> print(positions)
{'feelings': [0, 1, 8],
'like': [2, 9],
"i've": [3, 10],
'never': [4, 11],
'lost': [5],
'you': [6, 13],
'and': [7],
'have': [12]
}