[Python-ideas] collections.Counter multiplication

Steven D'Aprano steve at pearwood.info
Thu May 30 02:06:37 CEST 2013


On 30/05/13 06:17, James K wrote:
> It should work like this
>
>      >>> from collections import Counter
>      >>> Counter({'a': 1, 'b': 2}) * 2 # scalar
>      Counter({'b': 4, 'a': 2})

Under what circumstances would you do this?

What is it about Counters that they should support multiplication when no other mapping type does?

For what it is worth, the above is trivially doable using dict comprehensions:

py> from collections import Counter
py> count = Counter({'a': 2, 'b': 3})
py> Counter({k:v*2 for k,v in count.items()})
Counter({'b': 6, 'a': 4})


>      >>> Counter({'a': 1, 'b': 2}) * Counter({'c': 1, 'b': 2}) # multiplies
> matching keys
>      Counter({'b': 4})
>
>
> This is intuitive behavior and therefore should be added.

Not to me it isn't. I cannot guess what purpose this would hold, or why you would want to do this.


> I am unsure about
> division as dividing by a non-existing key would be a division by 0,
> although division by a scalar is straightforward.

Oh, so now you're proposing division as well? I presume you would want to support both / and // division, since they're both equally intuitive:

Counter({'a': 10})/3
=> Counter({'a': 3.3333333333333333})

Counter({'a': 10})//Counter({'a': 3, 'b': 4})
=> Counter({'a': 3, 'b': 0})

What about other operations, like ** & | ^ >> << ? Is it your proposal that Counters should support every operation that ints support?



-- 
Steven


More information about the Python-ideas mailing list