我有一个Tree类,我给它添加了一个in_order递归方法(似乎工作得很好).由于我想在我的Tree对象上进行迭代,我想我可以在下面实现同样的逻辑 接下来但是我得到了一个无限的生成器循环。
你能不能告诉我,我缺少什么?
class Tree:
def __init__(self, left=None, right=None, data=None):
self.data=data
self.right=right
self.left=left
def in_order(self):
if self.left is not None:
yield from self.left.in_order()
yield (self.data)
if self.right is not None:
yield from self.right.in_order()
def __iter__(self):
return self
def __next__(self):
if self.left is not None:
yield from self.left.__next__()
yield(self.data)
if self.right is not None:
yield from self.right.__next__()
t4 = Tree(data=5)
t6 = Tree(data=32)
t5 = Tree(data=10)
t1 = Tree(data=8, left=t4, right=t5)
t2 = Tree(data=35, left=t6)
t3 = Tree(left=t1, right=t2, data=20)
# Works well
gen = (t3.in_order())
for e in gen:
print(e)
# Gets into an infinite loop
for e in t3:
print(e)
评论的扩展版本。
class Tree:
# can be simplified with @dataclass
def __init__(self, left=None, right=None, data=None):
self.data=data
self.right=right
self.left=left
def __iter__(self):
if self.left is not None:
yield from self.left
yield (self.data)
if self.right is not None:
yield from self.right
in_order = __iter__
测试一下
t4 = Tree(data=5)
t6 = Tree(data=32)
t5 = Tree(data=10)
t1 = Tree(data=8, left=t4, right=t5)
t2 = Tree(data=35, left=t6)
t3 = Tree(left=t1, right=t2, data=20)
list(t3)
# returns [5, 8, 10, 20, 32, 35]
class Tree:
def __init__(self, left=None, right=None, data=None):
self.data=data
self.right=right
self.left=left
def in_order(self):
if self.left is not None:
yield from self.left.in_order()
yield (self.data)
if self.right is not None:
yield from self.right.in_order()
def __iter__(self):
if self.left is not None:
yield from self.left
yield(self.data)
if self.right is not None:
yield from self.right
t4 = Tree(data=5)
t6 = Tree(data=32)
t5 = Tree(data=10)
t1 = Tree(data=8, left=t4, right=t5)
t2 = Tree(data=35, left=t6)
t3 = Tree(left=t1, right=t2, data=20)
# Works well
gen = (t3.in_order())
for e in gen:
print(e)
# Works well
for e in t3:
print(e)
你在做一个无限的递归,当你在使用 yield
与 __next__
,如果你把它删除,问题就解决了。