一、概要
中缀表达式是我们经常接触的算术表达式,如(a+b)* c,a * (c - d)等,优点是便于记忆,缺点是对运算顺序有严格的要求。后缀表达式又称逆波兰式,如abc*+d e *f+g*+,虽然不便记忆,但是它不像中缀表达式,对于运算的顺序是没有要求,可以按照顺序扫描的方法计算表达式,因此在计算机内部容易用编程的方式实现表达式的求值。
二、中缀转后缀
# !/usr/bin/python
# coding=utf-8
# 中缀表达式转后缀表达式
# input: 中缀表达式
# output: 后缀表达式
def infix_to_suffix(inf):
stack = []
suf = ""
pt = i = -1
slen = len(inf) - 1
# {"operator" : "priority"}
opt_dict = {"(":3, ")":3, "+":1, "-":1, "*":2, "/":2}
while i < slen:
i += 1
char = inf[i]
if char not in opt_dict.keys():
suf += char.strip()
continue
# pop element util find '(' which should also be pop from stack
if char == ")":
while pt >= 0:
if stack[pt] == "(":
del stack[pt]
pt = pt - 1
break
suf += stack[pt]
del stack[pt]
pt = pt - 1
continue
# pop element whose level less than pri (priority)
# obviously, if is '(', 'break' make effect instantly
pri = opt_dict[char]
while pt >= 0:
if opt_dict[stack[pt]] < pri or stack[pt] == '(':
break
suf += stack[pt]
del stack[pt]
pt = pt - 1
stack.append(char.strip())
pt += 1
# output remainder of stack if possible
suf += "".join(stack)
return suf
def main():
inf = "a+b*c+(d*e+f)*g"
#inf = "a+b*c+(d*e+f)"
#inf = "(a+b)*(c*(d+e))"
suf = infix_to_suffix(inf)
print(suf)
if __name__ == '__main__':
main()
几点说明
- stack是一个列表,用来模拟栈,pt 指示栈顶;
- 不同运算符的优先级不同,相应的操作亦不同,详见注释;
- suf 表示最终输出的后缀表达式;
- 跳过空格,所以需要调用strip();
- 为方便起见,仅将“+,-,*,/”四种运算符和“()”考虑在内;
三、后缀转中缀
后缀转中缀相对比较简单。大致过程为:初始化一个空栈,然后顺序扫描表达式,如果不是运算符则压栈,否则从栈中相继弹出两个元素通过运算符做运算,并将运算后的表达式压栈。
# !/usr/bin/python
# coding=utf-8
# 后缀转中缀
# input: 后缀表达式
# output: 中缀表达式
def suffix_to_infix(suf):
opt_lst = ['+','-','*','/']
i = p = -1
explen = len(exp) - 1
stack = []
while i < explen:
i += 1
if exp[i] == ' ':
continue
if exp[i] in opt_lst:
# pop stack[p] and stack[p-1]
e1 = stack[p]
del stack[p]
p = p - 1
e2 = stack[p]
del stack[p]
p = p - 1
if exp[i] == "+" or exp[i] == "-":
e = str("(" + e2 + exp[i] + e1 + ")")
else:
e = str(e2 + exp[i] + e1)
p += 1
stack.append(e)
else:
# push to stack top
stack.append(exp[i])
p += 1
return stack[0]
def main():
#suf = "ab+cde+**"
suf = "abc*+de*f+g*+"
inf = suffix_to_infix(suf)
print(inf)
if __name__ == '__main__':
main()
说明:当发现“+,-”运算符时,对弹出的两个元素做运算后需要加上"()",这是为了保持原有的中缀表达式的运算优先级。可能会加一些多于的"()",但是运算不至于出错,此处可以优化,只是为了演示栈的应用没有实现。