| Infix Experssion | Prefix Expression | Postfix Expression |
|---|---|---|
| A + B * C | +A * B C | A B * C + |
| (A + B) * C | +A B * C | A B + C * |
Only infix expression need parentheses.
Steps for converting infix expression to postfix expression
-
1.Create an empty stack for keeping operators. Create an empty list for output.创建一个空的栈去保存运算符,并创建一个空的列表用来保存输出。 2.Convert the input infix string to a list by using the string method split.将输入的infix类型的字符串用string的split方法将其转变为列表。 3.Scan the token list from left to right.从左向右扫描这个列表。
- If the token is an operand, append it to the end of the output list. 如果从string列表中取出的是运算元,并将其放入保存输出的列表当中。
- If the token is a left parenthesis, push it on the stack.如果从列表中取出的是左括号,那么将其放入栈中。
- If the token is a right parenthesis, pop the stack until the corresponding left parenthesis is removed. Append each operator to the end of the output list.如果从列表中取出的是右括号,那么对栈使用pop方法直到与之相对应的左括号被移出。将括号间的所有运算符一一放入保存输出的列表中。 <

本文介绍了将中缀表达式转换为后缀表达式的方法,包括步骤和Python实现。在完全处理输入表达式后,检查栈并将所有剩余运算符添加到输出列表。内容基于Bradley N. Miller和David L. Ranum的《使用Python的问题解决算法和数据结构》,并由minnesota_gopher修改。
最低0.47元/天 解锁文章
1497

被折叠的 条评论
为什么被折叠?



