top | item 12352585

(no title)

ferrari8608 | 9 years 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.

discuss

order

jasonpeacock|9 years ago

NO. 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|9 years ago

Yup, 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|9 years ago

Or just `names[name] += 1` if you're using a Counter.

ferrari8608|9 years ago

Which would of course be the optimal solution. I always forget about that object.

tummybug|9 years ago

This is where `collections.defaultdict` shines