Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
n+k instead of n*k timing by iterating only once per array 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:
try:
c[w] += 1
except KeyError:
c[w] = 1
# is there a more elegant solution than this loop?
d = {}
for word in words:
try:
d[word] = c[word]
except KeyError:
d[word] = 0
return d
May 26, 2021
Comments: