multiset.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:multiset 作者: wheerd 项目源码 文件源码
def intersection(self, *others):
        r"""Return a new multiset with elements common to the multiset and all others.

        >>> ms = Multiset('aab')
        >>> sorted(ms.intersection('abc'))
        ['a', 'b']

        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('aaac'))
        ['a', 'a']

        For a variant of the operation which modifies the multiset in place see
        :meth:`intersection_update`.

        Args:
            others: The other sets intersect with 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 intersection of the sets.
        """
        result = self.__copy__()
        _elements = result._elements
        _total = result._total
        for other in map(self._as_mapping, others):
            for element, multiplicity in list(_elements.items()):
                new_multiplicity = other.get(element, 0)
                if new_multiplicity < multiplicity:
                    if new_multiplicity > 0:
                        _elements[element] = new_multiplicity
                        _total -= multiplicity - new_multiplicity
                    else:
                        del _elements[element]
                        _total -= multiplicity
        result._total = _total
        return result
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号