中缀表达式转换后缀表达式
建立一个运算符栈:
- 若是数字则直接输出
- 若是 ( ,压入栈中
- 若是 ) ,则出栈直到遇到 ( ,这里注意: ) 遇到的第一个 ( 一定是匹配的一对
- 遇到运算符,如果栈为空,则将其压栈
- 若是运算符, 比较该运算符与栈顶运算符的优先级,遇到比该运算符优先级大于或等于的则将其弹出,最后将该运算符压栈
代码实现
def postfix_exp(elements):
nums = ('0','1','2','3','4','5','6','7','8','9','.')
stack = list()
output = list()
flag = 0
for idx,ele in enumerate(elements):
if ele in nums or (flag==1 and ele=='-'):
# 若符号为 (, 那么它的后面可以是负数如(-3)
output.append(ele)
elif ele == '(': # '(' 在运算符中优先级最小,其唯一出栈条件时遇到右括号
stack.append(ele)
if elements[idx+3]==')': # 如果为负数那么一定是(-x), 则右括号一定在左括号右边第3个位置
flag = 1
elif ele == ')':
flag = 0 # 及时关闭带符号数的功能
val = stack.pop()
while val !='(':
output.append(val)
if stack: val = stack.pop()
else: break
elif ele in ('+','-','*','/'):
if len(stack) == 0:
stack.append(ele)
continue
# 若是 '+'、'-' 则 '+','-','*','/' 的优先级都大于等于它
# 若是'*','/' 则 '*','/' 的优先级都大于等于它
while (ele in ('*', '/') and stack[-1] in ('*', '/')) or \
(ele in ('+', '-') and stack[-1] != '('):
val = stack.pop()
output.append(val)
if not stack: # 防止空栈 pop
break
stack.append(ele)
while stack: # 当表达式完全处理完之后,把栈中的运算符一一出栈,FILO,转化成后缀表表达式
output.append(stack.pop())
return ''.join(output)
def test_postfix_exp():
a = '2+3*(7-4)+8/4' # >>> 2374-*+84/+
b = '((2+3)*4-(8+2))/5' # >>> 23+4*82+-5/
c = '(-2)*3' # >>> -23*
d = '1.3+25*12' # 1.32512*+
for i in [a,b,c,d]:
print(i+' >>> '+postfix_exp(i))