by ferrari8608 · 10y ago · 0 comments
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.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 :)
from collections import defaultdict
def count_names():
names = defaultdict(int)
for name in sys.stdin.readlines():
name = name.strip()
names[name] += 1
...