【问题标题】:How to create an abstract tree, rather than a postfix expression with the shunting yard algorithm?如何使用调车场算法创建抽象树,而不是后缀表达式?
【发布时间】:2017-03-28 06:04:59
【问题描述】:

我设法在 Wikipedia 上找到了以下伪代码,它展示了如何使用调车场算法来创建后修复表达式:

While there are tokens to be read:
    Read a token.
    If the token is a number, then push it to the output queue.
    If the token is a function token, then push it onto the stack.
    If the token is a function argument separator (e.g., a comma):
    Until the token at the top of the stack is a left parenthesis, pop              operators off the stack onto the output queue. If no left parentheses are encountered, either the separator was misplaced or parentheses were mismatched.
    If the token is an operator, o1, then:
        while there is an operator token o2, at the top of the operator stack and either
    o1 is left-associative and its precedence is less than or equal to that of o2, or
    o1 is right associative, and has precedence less than that of o2,
            pop o2 off the operator stack, onto the output queue;
    at the end of iteration push o1 onto the operator stack.
If the token is a left parenthesis (i.e. "("), then push it onto the stack.
If the token is a right parenthesis (i.e. ")"):
    Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue.
Pop the left parenthesis from the stack, but not onto the output queue.
If the token at the top of the stack is a function token, pop it onto the output queue.
If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.
When there are no more tokens to read:
    While there are still operator tokens in the stack:
        If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses.
        Pop the operator onto the output queue.
Exit.

如何修改此算法以生成抽象语法树,除了将运算符或操作数推送到输出之外,我应该做什么?

【问题讨论】:

  • 看看here.
  • 谢谢,我只是在做同样的事情,只是将操作数推送到表达式堆栈而不是输出。并将堆栈顶部的两个表达式与一个运算符连接起来,什么时候将其推送到输出?

标签: python algorithm python-3.x


【解决方案1】:

我想描述使用调车场算法构建 AST 的最简单方法,但不是最有效的方法。 这个想法只是使用该算法构建一个后缀字符串,然后从后缀字符串构建 AST,这非常容易。表达式,例如:a * (b + c) + d

它的后缀字符串:

a b c + * d +

让我们从后缀字符串中一个一个地读取标记。如果令牌是变量,则将其推送到带有节点的堆栈。如果它是一个操作数,让我们从带有节点的堆栈中弹出两个最高元素,创建另一个包含当前操作数的节点,并使两个提取的节点成为子节点。然后在节点堆栈中推送新节点。

最后,我们将在节点堆栈中只剩下一个节点——树的根。树就建好了。

这个算法需要两次读取字符串,这是一个明显的缺点。另一方面,它非常简单。

此处描述了更高效的算法,无需构建后缀字符串,而是立即使用调车场算法构建 AST:but it's in C++

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多