Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-使用生成器深度优先顺序迭代树_Python_Recursion_Generator_Yield_Depth First Search - Fatal编程技术网

Python-使用生成器深度优先顺序迭代树

Python-使用生成器深度优先顺序迭代树,python,recursion,generator,yield,depth-first-search,Python,Recursion,Generator,Yield,Depth First Search,我正在尝试在二叉树上进行DFS。这棵树是有效的。当产量被打印替换时(当它不是生成器时),该函数本身起作用 编辑:摘自主要内容: tree = BinaryTree(15) #adds the key 15 as the root tree.addKey(10) #adds additional entries ... tree.addKey(5) depthFirstSearch = tree.dfs() for i in range(8): print depthFirs

我正在尝试在二叉树上进行DFS。这棵树是有效的。当产量被打印替换时(当它不是生成器时),该函数本身起作用

编辑:摘自主要内容:

tree = BinaryTree(15) #adds the key 15 as the root
tree.addKey(10)       #adds additional entries
...
tree.addKey(5)
depthFirstSearch = tree.dfs()
for i in range(8): 
    print depthFirstSearch.next()
    print "outside of fnc"
为完整起见,该树如下所示:

{15: {10: {3: {2: , }, {5: , }}, }, {17: , {60: {23: , }, }}}
Depth First
Starts 
15
outside of fnc
keep it up left
keep it up right
oh no
输出如下所示:

{15: {10: {3: {2: , }, {5: , }}, }, {17: , {60: {23: , }, }}}
Depth First
Starts 
15
outside of fnc
keep it up left
keep it up right
oh no

很明显,由于“保持运行”调试行,节点就在那里。不过,它似乎跳过了递归步骤。否则它将重新开始打印。我尝试过在self.depth(Node.right)语句中添加一个yield,但这似乎没有任何帮助。返回语句在生成器内部也不好,这对我来说是有意义的。谢谢

BinaryTree.depth
中,您正在递归,但没有对递归调用执行任何操作

例如:

self.depth(Node.left)
应该是

for node in self.depth(Node.left):
    yield node
在Python3.3+中,它可以简单到

yield from self.depth(Node.left)
“main”中的for循环应如下所示:

for node in depthFirstSearch:
    print node

我还注意到你的深度优先搜索算法有正确的想法,但你实际上还没有搜索任何东西。不过,我猜您已经知道了。

您是否介意展示一下如何定义
depthFirstSearch
?很抱歉,请参阅编辑。我主要知道for循环。我一直在尝试学习生成器,并希望更改迭代次数,以便能够处理StopIteration异常。如果我是递归的,为什么“开始”只打印一次?你的回答很有魅力。我想这是发电机的本质。懒惰的评估?@Chet,你是对的。通过查看代码,您可以看到您已经知道这一点。Python认识到任何使用
yield
的函数都是生成器。因此,当调用生成器时,它将生成迭代器的新实例。在
BinaryTree.dfs
方法中,返回生成的迭代器。然而,在您的
BinaryTree.depth
方法中,您正在生成新的迭代器,但没有对它们进行任何操作。它们是创建的,但从未使用过。这就是为什么必须在循环中生成每个节点。另外,根据我的经验,您很少需要显式地使用
StopIteration