[Python-ideas] collections.Counter should implement __mul__, __rmul__
Serhiy Storchaka
storchaka at gmail.com
Wed Apr 18 16:29:04 EDT 2018
18.04.18 21:45, Tim Peters пише:
> (*) The obvious implementation:
>
> def __mul__(self, other):
> if isinstance(other, Sized):
> raise TypeError("cannot multiply Counter by Sized type %s"
> % type(other))
Wouldn't be better to return NotImplemented here?
> result = Counter()
> for k, v in self.items():
> result[k] = v * other
> return result
If discard non-positive values, this will automatically make multiplying
Counter by Counter (or by sequence) invalid, because they are not
comparable with 0.
for k, v in self.items():
v = v * other
if v > 0:
result[k] = v * other
More information about the Python-ideas
mailing list