ZH奶酪:Python 中缀表达式转换后缀表达式

实现一个可以处理加减乘数运算的中缀表达式转换后缀表达式的程序:

一个输入中缀表达式inOrder

一个输出池pool

一个缓存栈stack

从前至后逐字读取inOrder

首先看一下不包含括号的:

(1)操作数:直接输出到pool

(2)操作符:判断当前操作符与stack[top]操作符的优先级

  <1>当前操作符优先级高于stack[top]:将当前操作符添加到stack中;

  <2>当前操作符优先级低于或等于stack[top]:从stack[top]开始出栈,直到stack[top]优先级高于当前操作符,然后将当前操作符入栈;

(3)当inOrder遍历结束,如果stack非空,反转stack,添加到pool尾

 __author__ = 'ZhangHe'
def in2post(inOrder):
pool = ''
stack = ''
for i in inOrder:
ret = proc(i,switch(i),stack,pool)
stack = ret['stack']
pool = ret['pool']
if stack != '':
stack = stack[::-1]
return pool+stack def switch(c):
operator1 = '+-'
operator2 = '*/'
num = 'abcdefg'
if c in num:
return 0
if c in operator1:
return 1
if c in operator2:
return 2
def proc(c,op,stack,pool):
top = len(stack)-1 if op == 0:#abcdefg
pool += c
if op == 2 or op==1:#*
if top == -1:
stack += c
elif switch(stack[top]) < op:
stack += c
else:
while top != -1 and switch(stack[top]) >= op:
pool += stack[top]
top -= 1
if top != -1:
stack = stack[0:top+1]
else:
stack = ''
stack += c
ret = {
'stack':stack,
'pool':pool
}
return ret
inOrder = 'a+b*c-d*e+f/g'
48 print in2post(inOrder)

当包含括号的时候应该考虑哪些因素呢?

在上个程序的基础上,进一步考虑下边的几点:

(4)加入括号之后,“(”拥有最高优先级,也就是说,遇到“(”就放到stack中就好了;

(5)遇到“)”的操作也比较简单,直接把stack中的元素逐一弹出到pool,直到弹出“(”;

此时需要新的操作符规则:

(5)操作符:判断当前操作符与stack[top]操作符的优先级

  <1>当前操作符优先级高于stack[top]或者stack[top]==‘(’:将当前操作符添加到stack中;

  <2>当前操作符优先级低于或等于stack[top]:从stack[top]开始出栈,直到stack[top]优先级高于当前操作符或者stack[top]为“(”,然后将当前操作符入栈;

 __author__ = 'ZhangHe'
def in2post(inOrder):
pool = ''
stack = ''
for i in inOrder:
ret = proc(i,switch(i),stack,pool)
stack = ret['stack']
pool = ret['pool']
if stack != '':
stack = stack[::-1]
return pool+stack def switch(c):
operator1 = '+-'
operator2 = '*/'
operator3 = ')'
operator4 = '('
num = 'abcdefg'
if c in num:
return 0
if c in operator1:
return 1
if c in operator2:
return 2
if c in operator3:
return 3
if c in operator4:
return 4
def proc(c,op,stack,pool):
top = len(stack)-1 if op == 0:#abcdefg
pool += c
if op == 2 or op==1:#*
if top == -1:
stack += c
elif switch(stack[top]) < op or stack[top] == '(':
stack += c
else:
while top != -1 and switch(stack[top]) >= op and switch(stack[top])<switch(')'):
pool += stack[top]
top -= 1
if top != -1:
stack = stack[0:top+1]
else:
stack = ''
stack += c
if op == 3:#)
while top!= -1 and stack[top] != '(':
pool += stack[top]
top -= 1
stack = stack[0:top]
if op == 4:#(
stack += c
ret = {
'stack':stack,
'pool':pool
}
return ret
# inOrder = 'a+b*c-d*e+f/g'
inOrder = 'a+b*c+(d*e+f)*g'
print in2post(inOrder)

输出:

abc*+de*f+g*+

上一篇:zzulioj 1206 字符串的修改 (字符串修改)


下一篇:02 Architecture Overview