首页 > 解决方案 > 将多重集 javaCode 联合到 python(在范围内)

问题描述

我在将 Java 中的 Multiset 类转换为 Python 时遇到了麻烦。我对这段 Java 代码到 Python 有一个特殊的问题:

public Multiset unionWith(Multiset other)
{
    Multiset result = new Multiset();

    for ( Object object : elts.keySet() )
    {
        for ( int i = 0; i != elts.get(object); ++i )
        {
            result.add(object);
        }
    }

    for ( Object object : other.elts.keySet() )
    {
        for ( int i = 0; i != other.elts.get(object); ++i )
        {
            result.add(object);
        }
    }

    return result;
}

}

这是我制作的整个班级。除了unionWith,一切似乎都有效,我不知道。我很确定问题出在“范围内”,有条件。这在 python 中是如何工作的?

class Multiset:
def __init__(self):
   self.elts= dict()

def contains(self, o):
    if o in self.elts.keys():
        return True
    else:
        return False

def add(self, o):
    if self.contains(o):
        newValue = self.elts.get(o) + 1
        self.elts[o] = newValue
    else:
        self.elts[o] = 1

def remove(self, o):
    if self.contains(o):
        newValue = self.elts.get(o) - 1

        if newValue > 0:
            self.elts[o] = newValue
        else:
            del self.elts[o]


def elements(self):
    return set(self.elts.keys())
@property
def size(self):
    total = 0

    for object in self.elts.values():
        total = total + self.elts.get(object)

    return total
def unionWith(self,other):
    result= Multiset()

    for object in self.elts.values():

        for i in range(0):
            if i is not self.elts.get(object):
                break
            result.add(object)

    for object in other.elts.values():
        for i in range(0):
            if i is not other.get(object):
                break
            result.add(object)

标签: javapython

解决方案


我建议您使用魔术方法使您的类与 python 语言更加集成,例如__iter____contains__

import collections
import itertools

class Multiset:
    def __init__(self, iterable=None):
        self._data = collections.defaultdict(int)
        if iterable:
            self._data.update(collections.Counter(iterable))

    def __contains__(self, element):
        return element in self._data

    def add(self, element):
        self._data[element] += 1

    def remove(self, element):
        if element not in _data:
            raise KeyError(element)
        elif self._data[element] == 1:
            del self._data[element]
        else:
            self._data[element] -= 1

    def update(self, iterable):
        data = collections.Counter(self._data) + collections.Counter(iterable)
        self._data = collections.defaultdict(int)
        self._data.update(data)

    def elements(self):
        return self._data.keys()

    def __len__(self):
        return sum(self._data.values())

    def __iter__(self):
        return itertools.chain.from_iterable(
            itertools.repeat(element, number) 
                for element, number in self._data.items()
        )

    def union(self, other):
        result = Multiset(self)
        result.update(other)
        return result

    def __repr__(self):
        return 'Multiset([{}])'.format(
            ', '.join(repr(element) for element in self))

测试:

>>> s = Multiset()
>>> s
Multiset([])
>>> s.update('abca')
>>> s
Multiset(['a', 'a', 'c', 'b'])
>>> len(s) # calls __len__
>>> 'a' in s  # calls __contains__
True
>>> r = Multiset('zxc')
>>> r
Multiset(['x', 'c', 'z'])
>>> s.union(r)
Multiset(['a', 'a', 'x', 'c', 'c', 'b', 'z'])

可以实现更多,例如__add____sub__(差异),intersection...


推荐阅读