将multiset javaCode联合到python(范围内)

时间:2018-07-19 12:43:04

标签: java 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)

1 个答案:

答案 0 :(得分:0)

我建议您使用魔术方法使您的类与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 ...