Hacker News new | past | comments | ask | show | jobs | submit login

You can also use the set-comprehension syntax, which functions equivalently but looks slightly nicer:

    return {w for w in words if w in WORDS}
could have also directly used the intersection operator on the sets:

    return words & WORDS
or slightly more verbose, but maybe more clear for colleagues who don't regularly use sets in Python:

    return words.intersection(WORDS)



> return words & WORDS

Not quite. It'd have to be set(WORDS) instead of WORDS -- which'd be expensive. Or WORDS.keys(), which I'm not sure about -- I'd have to benchmark it.


You would only need to do set(WORDS) once at the beginning of the program, so its amortized cost is low.


I wouldn't worry about the expense of set construction vs the expense of an n-squared algorithm.


caught me, I hadn't read through the article, wasn't sure whether or not WORDS was a set or a dict. Like desdiv points out, this isn't a big deal, you can maintain an equivalent WORDS structure that is a set.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: