This is an old question, but I just had the same issue during chemical formulae parsing. I extended the Counter
class to accept multiplication with integers. For my case, the following is sufficient - it may be extended on demand:
class MCounter(Counter):
"""This is a slight extention of the ``Collections.Counter`` class
to also allow multiplication with integers."""
def __mul__(self, other):
if not isinstance(other, int):
raise TypeError("Non-int factor")
return MCounter({k: other * v for k, v in self.items()})
def __rmul__(self, other):
return self * other # call __mul__
def __add__(self, other):
return MCounter(super().__add__(other))
So with above, you can multiply from left and right with integers as well. I needed to redefine __add__
such that the type MCounter
was preserved. If one needs to use subtraction, &
and |
, that needs to be implemented likewise.
2
? – Spitter