使用Iterator类迭代DictSet时的KeyError

时间:2015-12-15 20:39:36

标签: python iterator

我创建了一个Set类,它具有集合类型,ListSet和DictSet,分别由列表和字典表示。两个集都需要是可迭代的,我已经创建了一个SetIterator类,但是当我尝试测试DictSet时,我得到以下错误:

Traceback (most recent call last):
  File "Set.py", line 118, in <module>
    inter = e.intersection(t)
  File "Set.py", line 22, in intersection
    if element in other:
  File "Set.py", line 8, in __next__
    current_element = self.elements[self.index]
KeyError: 0

似乎我的SetIterator类中有一个错误,我尝试重写我认为导致错误的行,但它没有修复任何东西

def new(obj, *args, **kwargs):
    return type(obj)(*args, **kwargs)


class SetIterator:
    def __init__(self, s):
        self.elements = s.members()
        self.index = 0

    def __next__(self):
        try:
            current_element = self.elements[self.index]
        except IndexError:
            raise StopIteration()
        self.index += 1
        return current_element


class Set:
    def __iter__(self):
        return SetIterator(self)

    def intersection(self, other):
        new_set = new(self)  # to hold intersected set
        for element in self:
            if element in other:
                new_set.add(element)
        return new_set

    def union(self, other):
        new_set = new(self)  # to hold unionized set
        for element in self:
            new_set.add(element)
        for element in other:
            if element not in new_set:
                new_set.add(element)
        return sorted(new_set)

    def difference(self, other):
        new_set = new(self) #to hold set difference
        for element in self:
            if element not in other:
                new_set.add(element)
        return new_set

    def equals(self, other):
        new_set = new(self)
        other_set = new(self)
        for element in self:
            if element in other:
                new_set.add(element)
        for element in other:
            if element in self:
                other_set.add(element)
        if new_set == other_set:
            return True
        else:
            return False

    def notEmpty(self):
        empty_set = new(self)
        placeholder = new(self)
        for element in self:
            placeholder.add(element)
        if empty_set == placeholder:    # If both are equal
            return False    # means self is empty
        else:
            return True # means self is not empty
class DictSet(Set):
    def __init__(self, elements=[]):
        rep = self.rep = {}
        for element in elements:
            rep[element] = element

    def add(self, x):
        self.rep[x] = x

# Testing code
if __name__ == '__main__':
    e = DictSet([1, 2, 3, 4, 19, 31, 27, 0])
    t = DictSet([1, 2, 3, 4])
    print(t.rep)

    # Testing DictSet
    inter = e.intersection(t)
    uni = e.union(t)
    diff = e.difference(t)
    eq = e.equals(t)

    print('The intersection of the DictSets is:', inter)
    print('The union of the Dictsets is:', uni)
    print('The difference of the DictSets is:', diff)
    print('Are the two DictSets equal?', eq)

我尝试将SetIterator重写为:

class SetIterator:
    def __init__(self, s):
        self.elements = **s.rep**
        self.index = 0

    def __next__(self):
        try:
            current_element = self.elements[self.index]
        except IndexError:
            raise StopIteration()
        self.index += 1
        return current_element

但是我仍然得到相同的错误,我的ListSet打印出正确的集合。

0 个答案:

没有答案