哈希集

2024-06-01 07:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,在过去的一周左右,我一直在做一些HashSet问题。最后一个问题要求我为HashSet创建iter方法。这是我的代码:

class HashSet:
    def __init__(self, capacity=10):
        self.table = [None] * capacity

    def add(self, item):
        h = hash(item)
        index = h % len(self.table)

        if self.table[index] == None:
            self.table[index] = LinkedList() 

        if item not in self.table[index]:
            self.table[index].add(item)

    def __iter__(self):
        table = []
        ptr = None
        for i in range(0, len(self.table)):
            if self.table[i]:
                ptr = self.table[i].head
                while ptr != None:
                    table.append(ptr.item)
                    ptr = ptr.next
        return sorted(table)

它似乎不起作用,它给了我一个错误:TypeError:iter()返回了“list”类型的非迭代器。我应该还什么??在

输入:7 20 30 40 50 60 70 80 90
期望输出:[20, 30, 40, 50, 60, 70, 80, 90]

我用print()语句测试了表var中的值是否正确。我怎么修?在


Tags: 方法inselfnoneaddindexlenif
1条回答
网友
1楼 · 发布于 2024-06-01 07:45:30

应返回迭代器或使用yield from委托迭代:

def __iter__(self):
    ...
    return iter(sorted(table)) # creates an iterator from the list

或者

^{pr2}$

相关问题 更多 >