4 ms·
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 a
by kough 10y ago
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)
- abecedarius 10y ago> 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.
- xapata 10y agoI wouldn't worry about the expense of set construction vs the expense of an n-squared algorithm.
- deleted 10y ago[deleted]
- desdiv 10y agoYou would only need to do set(WORDS) once at the beginning of the program, so its amortized cost is low.
- kough 10y agocaught 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.