5 ms·
# Avoid this lyrics_list = ['her', 'name', 'is', 'rio'] words = make_wordlist() # Pretend this returns many words that we want to test for word in words:
by gr3yh47 12y ago
# Avoid this
lyrics_list = ['her', 'name', 'is', 'rio']
words = make_wordlist() # Pretend this returns many words that we want to test
for word in words:
if word in lyrics_list: # Linear time
print word, "is in the lyrics"
# Do this
lyrics_list = ['her', 'name', 'is', 'rio']
lyrics_set = set(lyrics_list) # Linear time set construction
words = make_wordlist() # Pretend this returns many words
that we want to test
for word in words:
if word in lyrics_list: # Constant time
print word, "is in the lyrics"
the second example should read ... if word in lyrics_set: ...
- darkxanthos 12y agoJust to point out, if you really will have a tiny list and that's knowable, it's possible this example would be best with a straight linear time check. It could be fewer operations than hashing a string and looking it up. Practically pedantry though.
- constantine_ 12y agoThanks for pointing out this mistake. It's now fixed.