Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
n+k versus n*k performance solution in Speedy category for Popular Words by leggewie
## one-liner, creating the dict on the fly. timing is n*k
#def popular_words(text: str, words: list) -> dict:
# return {word:text.lower().split().count(word) for word in words}
# much longer but faster. timing is n+k instead of n*k
# iterating only once over the text and words arrays
def popular_words(text: str, words: list) -> dict:
ltext = text.lower().split()
# is there a more elegant solution than this loop?
c = {}
for w in ltext:
c[w] = c.get(w, 0) + 1
# is there a more elegant solution than this loop?
d = {}
for word in words:
d[word] = c.get(word, 0)
return d
May 26, 2021
Comments: