def combine(self, *others):
r"""Return a new multiset with all elements from the multiset and the others with their multiplicities summed up.
>>> ms = Multiset('aab')
>>> sorted(ms.combine('bc'))
['a', 'a', 'b', 'b', 'c']
You can also use the ``+`` operator for the same effect. However, the operator version
will only accept a set as other operator, not any iterable, to avoid errors.
>>> ms = Multiset('aab')
>>> sorted(ms + Multiset('a'))
['a', 'a', 'a', 'b']
For a variant of the operation which modifies the multiset in place see
:meth:`update`.
Args:
others: The other sets to add to the multiset. Can also be any :class:`~typing.Iterable`\[~T]
or :class:`~typing.Mapping`\[~T, :class:`int`] which are then converted to :class:`Multiset`\[~T].
Returns:
The multiset resulting from the addition of the sets.
"""
result = self.__copy__()
_elements = result._elements
_total = result._total
for other in map(self._as_mapping, others):
for element, multiplicity in other.items():
old_multiplicity = _elements.get(element, 0)
new_multiplicity = old_multiplicity + multiplicity
if old_multiplicity > 0 and new_multiplicity <= 0:
del _elements[element]
_total -= old_multiplicity
elif new_multiplicity > 0:
_elements[element] = new_multiplicity
_total += multiplicity
result._total = _total
return result
评论列表
文章目录