[Python-ideas] collections.Counter should implement __mul__, __rmul__

Serhiy Storchaka storchaka at gmail.com
Wed Apr 18 12:26:44 EDT 2018


16.04.18 08:07, Tim Peters пише:
> Adding Counter * integer doesn't bother me a bit, but the definition
> of what that should compute isn't obvious.  In particular, that
> implementation doesn't preserve that `x+x == 2*x` if x has any
> negative values:
> 
>>>> x = Counter(a=-1)
>>>> x
> Counter({'a': -1})
>>>> x+x
> Counter()
> 
> It would be strange if x+x != 2*x, and if x*-1 != -x:
> 
>>>> y = Counter(a=1)
>>>> y
> Counter({'a': 1})
>>>> -y
> Counter()
> 
> Etc.
> 
> Then again, it's already the case that, e.g., x-y isn't always the
> same as x + -y:
> 
>>>> x = Counter(a=1)
>>>> y = Counter(a=2)
>>>> x - y
> Counter()
>>>> x + -y
> Counter({'a': 1})
> 
> So screw obvious formal identities ;-)
> 
> I'm not clear on why "+" and "-" discard keys with values <= 0 to
> begin with.  For "-" it's natural enough viewing "-" as being multiset
> difference, but for "+"?  That's just made up ;-)
> 
> In any case, despite the oddities, I think your implementation would
> be least surprising overall (ignore the sign of the resulting values).
> At least for Counters that actually make sense as multisets (have no
> values <= 0), and for a positive integer multiplier `n > 0`, it does
> preserve that `x*n` = `x + x + ... + x` (with  `n` instances of `x`).

There are methods update() and subtract() which are similar to operators 
"+" and "-", but don't discard non-positive values.

I expect that "*" and "/" discard non-positive values for consistency 
with "+" and "-". And a new method should be added which does 
multiplication without discarding non-positive values.



More information about the Python-ideas mailing list