用Python将中缀转换为后缀的算法

问题描述 投票:0回答:1

我正在尝试用Python编写以下算法(以普通英语提供),用于将简单的数学表达式从中缀形式转换为后缀形式:

Create a new empty list, *operators*
Create a new empty list, *postfix*

**For** each token in the infix expression
  **If** the token is an integer **then**
    Append the token to *postfix*
  **If** the token is an operator **then**
    **While** *operators* is not empty and the last item in *operators* is not an open parenthesis and              precedence(token) < precedence(last item in *operators*) **do**
        Remove the last item from *operators* and append it to *postfix*
      Append the token to *operators*
  **If** the token is an open parenthesis **then**
    Append the token to *operators*
  **If** the token is a close parenthesis **then**
    **While** the last item in *operators* is not an open parenthesis **do**
        Remove the last item from *operators* and append it to *postfix*
      Remove the open parenthesis from *operators*

**While** *operators* is not the empty list **do**
  Remove the last item from *operators* and append it to *postfix*

**Return** *postfix* as the result of the algorithm

但是,我对“从 operators 中删除左括号”这一行有点困惑。我曾经见过 operators 中同时存在多个左括号的情况。在这种情况下,应该删除哪一个?

python algorithm postfix-notation infix-notation mathematical-expressions
1个回答
0
投票

当然是你刚刚找到的那个。不要忘记上下文:

    **While** the last item in *operators* is not an open parenthesis **do**
        Remove the last item from *operators* and append it to *postfix*
      Remove the open parenthesis from *operators*

while 循环删除了一些内容,直到 operators is 中的最后一项是一个左括号,然后删除该项目。

© www.soinside.com 2019 - 2024. All rights reserved.