I am creating a function that counts the occurrences of searched_words in a passed string. The result is a dictionary with the matching words as keys and their occurrences as values.
I have already created a function that accomplishes this but it is very poorly optimized.
def get_words(string, searched_words):
words = string.split()
# O(nm) where n is length of words and m is length of searched_words
found_words = [x for x in words if x in searched_words]
# O(n^2) where n is length of found_words
words_dict = {}
for word in found_words:
words_dict[word] = found_words.count(word)
return words_dict
print(get_words('pizza pizza is very cool cool cool', ['cool', 'pizza']))
# Results in {'pizza': 2, 'cool': 3}
I have attempted to use the Counter functionality from Python's collections model but cannot seem to reproduce the desired output. It seems using the set datatype may also solve my optimization problem but I am unsure of how to count word occurrences while using sets.