Convert infix to postfix in Python

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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方法直到与之相对应的左括号被移出。将括号间的所有运算符一一放入保存输出的列表中。
If the token is an
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值