你好,在过去的一周左右,我一直在做一些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中的值是否正确。我怎么修?在
应返回迭代器或使用
yield from
委托迭代:或者
^{pr2}$相关问题 更多 >
编程相关推荐