6 ms·
Came here to say this. I've combed through his pieces many times over just to glean the way he structures his code. Here, he got my head spinning for a minute w
by leblancfg 10y ago
Came here to say this. I've combed through his pieces many times over just to glean the way he structures his code. Here, he got my head spinning for a minute with
return set(w for w in words if w in WORDS)
and made a mental note to use that idiom in the future.
As for doc strings, well, this is just a toy piece of code after all. The main purpose for the code is to be read, instead of actually used. something something hobgoblin of little minds
Edit: formatting.
- kough 10y agoYou 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.
- misiti3780 10y agothat is a great idiom. i remember the first time i saw it (possibly in is very essay), i thought it was awesome. I use it all over the place now. it is similiar to the javascript ternary operator [1], which I also find to be very useful var varX = (boolean) ? 'X' : 'Y' [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- nommm-nommm 10y agoPretty much every language has a ternary conditional operator: C++, Java, Python, C#, Ruby....
- kevin_thibedeau 10y agoThis isn't the Python ternary which is: varX = 'X' if boolean else 'Y' # And is chainable in a more natural way than C*: varX = 'X' if boolean else 'Y' if other else 'Z'
- crgt 10y agoThat was one of the phrases used in the program that taught me to touch type. Stuck with me for decades..and has been almost as useful to me as learning to touch type...
- crgt 10y agoThat was one of the phrases used in the program that taught me to touch type. Stuck with me for decades..and has been almost as useful to me as learning to touch type...