4 ms·
I just wanted to point out a bit of syntax from the article. I'm a huge fan of compact variable declaration if statements. The code from the article: if na
by ferrari8608 10y ago
I just wanted to point out a bit of syntax from the article. I'm a huge fan of compact variable declaration if statements. The code from the article:
if name in names:
names[name] += 1
else:
names[name] = 1
That can actually be written as just one neat, readable line:
names[name] = names[name] + 1 if name in names else 1
It may not be as readable to some who are used to spelling it out as an if/else block, but I really prefer the one line way. It reads closer to regular English I think.
- jasonpeacock 10y agoNO. That is not more readable, and is warned against in most style guides and code-quality books. In the original, at a glance I know exactly what is going on. In your version, I have to read the whole sentence carefully to notice that it's even a conditional and not a normal assignment, and then I have to mentally unpack it to understand the logic that you're trying to implement. If/else should never be a one-liner. Good code is boring code :)
- avyfain 10y agoYup, but the right way to do it would be a defaultdict, or a Counter anyway. from collections import defaultdict def count_names(): names = defaultdict(int) for name in sys.stdin.readlines(): name = name.strip() names[name] += 1 ...
- orf 10y agoOr just `names[name] += 1` if you're using a Counter.
- ferrari8608 10y agoWhich would of course be the optimal solution. I always forget about that object.
- tummybug 10y agoThis is where `collections.defaultdict` shines