MCPcopy Create free account
hub / github.com/ActiveState/code / __imul__

Method __imul__

recipes/Python/578612_Counter_class/recipe-578612.py:224–255  ·  view source on GitHub ↗

Multiply bag contents by factor. >>> b = Bag.fromkeys("abacab") >>> b *= 4 >>> print(b) {'a': 12, 'b': 8, 'c': 4} Negative factors can be used with IntegerBag. >>> ib = IntegerBag(b) >>> ib *= -1 >>> print(ib) {'a': -12, 'b':

(self, factor)

Source from the content-addressed store, hash-verified

222 return self.__class__(self).__isub__(other)
223
224 def __imul__(self, factor):
225 """Multiply bag contents by factor.
226
227 >>> b = Bag.fromkeys("abacab")
228 >>> b *= 4
229 >>> print(b)
230 {'a': 12, 'b': 8, 'c': 4}
231
232 Negative factors can be used with IntegerBag.
233 >>> ib = IntegerBag(b)
234 >>> ib *= -1
235 >>> print(ib)
236 {'a': -12, 'b': -8, 'c': -4}
237
238 Trying that on a Bag will return empty bag (akin to list behavior).
239 >>> b *= -1
240 >>> b
241 {}
242
243 Zero factors will return empty bag.
244 >>> b += "abacab"
245 >>> b *= 0
246 >>> b
247 {}
248
249 """
250 if self._filter(factor):
251 for item, count in self.items():
252 dict.__setitem__(self, item, count*factor) #bypass test logic in bag.__setitem__
253 else: #factor==0 or negative on Bag
254 dict.clear(self) #call dict.clear to protect subclass which might override and do other things besides clear dict values
255 return self
256
257 def __mul__(self, factor):
258 """Returns new bag of same type multiplied by factor.

Callers 1

__mul__Method · 0.45

Calls 4

_filterMethod · 0.95
itemsMethod · 0.45
__setitem__Method · 0.45
clearMethod · 0.45

Tested by

no test coverage detected