【问题标题】:Generator Function for inOrder traversal用于 inOrder 遍历的生成器函数
【发布时间】:2018-07-07 21:51:21
【问题描述】:

我最近一直在研究我的生成器函数和表达式,但我不太确定如何解决这个问题。我如何使用生成器函数来生成然后按顺序打印值?

我使用 pythons 列表构建了我的 BST

bst = [20, [10, [5, [2, [], []], [8, [], []]], [15, [], []]], [30, [25, [22, [], []], [27, [], []]], [35, [], [37, [], []]]]]

如果我要打印中序遍历,我没有问题。因此,如果我要为以下功能调用 inorder(bst)

def inorder(tree):
    if tree:
        inorder(tree[1])
        print (tree[0])
        inorder(tree[2])

我得到了这个输出。

2
5
8
10
15
20
22
25
27
30
35
37

我认为生成器表达式同样简单

def inorder(tree):
    if tree:
        inorder(tree[1])
        yield (tree[0])
        inorder(tree[2])

我遇到的问题是让我的 main 迭代函数中产生的内容。我以为应该是这样的

test= inorder(bst)

for i in range(0,len(l)): # l is the number of items in bst
    print (next(test))

它不是迭代整个函数 yield ,而是在它开始之前简单地停止迭代。

    20
Traceback (most recent call last):
  File "functionGenerator.py", line 64, in <module>
    print(next(test))
StopIteration

我需要做什么才能使我的函数发生器正常运行?

【问题讨论】:

  • 您的语法错误与生成器无关,您在 Python 3 中使用的是 Python 2 语法。
  • 好吧,python 3 的语法会变成什么样子?
  • print(next(test))
  • 您在原来的inorder() 实现中使用它...
  • 您的递归 inorder() 但是还有其他问题;您需要使用yield from inorder(tree[1])for res in inorder(tree[1]): yield res

标签: python generator


【解决方案1】:

您的 inorder() 实现没有正确递归。您只打印树的当前顶部节点。那是因为只调用inorder(tree[1])inorder(tree[2]) 返回一个生成器对象,你并没有迭代这些生成器。

使用

def inorder(tree):
    if tree:
        yield from inorder(tree[1])
        yield tree[0]
        yield from inorder(tree[2])

yield from expression 将生成器委托给另一个生成器,从该子生成器产生直到完成。这样你就可以正确地递归了。

如果您使用的是较旧的 Python 版本(Python 3.3 之前),则需要手动迭代递归调用:

def inorder(tree):
    if tree:
        for sub in inorder(tree[1]):
            yield sub
        yield tree[0]
        for sub in inorder(tree[2]):
            yield sub

接下来,您可以迭代 inorder() 生成器:

>>> for node in inorder(bst):
...     print(node)
...
2
5
8
10
15
20
22
25
27
30
35
37

虽然使用next() 也可以:

>>> tree = inorder(bst)
>>> print(next(tree))
2
>>> print(next(tree))
5

但迭代更简洁,一旦引发StopIteration 就会自动停止。

【讨论】:

  • 谢谢,我将确保在以后的问题中遵循最小的完整且可验证的示例。
猜你喜欢
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 2021-12-04
  • 2016-08-22
  • 2014-07-20
  • 2016-11-05
相关资源
最近更新 更多