用python实现算式的运算:
利用栈将中缀表达式转化为后缀表达式,再对后缀表达式进行计算
"""
-*- coding: utf-8 -*-
@Time : 2022/3/15 20:37
@Author : wcc
@FileName: arithmeticOperation.py
@Software: PyCharm
@Blog :https://blog.csdn.net/qq_41575517?spm=1000.2115.3001.5343
"""
# 栈的结构
class Stack(object):
def __init__(self, stack, top):
self.stack = stack
self.top = top
# 中缀转后缀
def middle2behind(formula):
behind = []
s = Stack(stack=[], top=-1)
# 遍历表达式
for i in formula:
# 如果表达式元素为+或-,由于+或-的运算优先级最低,所以如果栈为非空,则从栈顶开始遍历栈符号,依次出栈,直到栈为空或者是遇到(
if i == '+' or i == '-':
if s.top > -1:
while s.top > -1 and s.stack[s.top] != '(':
behind.append(s.stack[s.top])
s.stack.pop()
s.top -= 1
# 将此时在表达式中遍历的这个符号入栈,也就是i
s.stack.append(i)
s.top += 1
# 如果栈为空,直接入栈
else:
s.stack.append(i)
s.top += 1
# 如果表达式元素为*或/,由于*或/的运算优先级较高,所以如果栈为非空,则从栈顶开始遍历栈内符号,如果
# 遇到*或者/,则依次出栈,直到栈为空或者是遇到(和+和-
elif i == '*' or i == '/':
if s.top > -1 and s.stack[s.top] != '(':
while s.stack[s.top] == '*' and s.stack[s.top] == '/':
behind.append(s.stack[s.top])
s.stack.pop()
s.top -= 1
s.stack.append(i)
s.top += 1
else:
s.stack.append(i)
s.top += 1
# 如果遇到(,则直接入栈,直到匹配到)后将栈中()内的符号全部出栈
elif i == '(':
s.stack.append(i)
s.top += 1
elif i == ')':
while s.stack[s.top] != '(':
behind.append(s.stack[s.top])
s.stack.pop()
s.top -= 1
s.stack.pop()
s.top -= 1
else:
behind.append(i)
# 把栈中剩余的符号出栈
while s.top > -1:
behind.append(s.stack[s.top])
s.stack.pop()
s.top -= 1
return behind
# 遍历后缀表达式,如果遇到数字,将其放入栈中,如果遇到符号,则取出栈中最顶上的两个数字进行
# 计算,最顶上的那个数字是右项。运算完成之后将结果再存回栈中
def behindCalculation(behind):
result = Stack(stack=[], top=-1)
r = 0
for i in behind:
if i == "+":
r = int(result.stack[result.top-1]) + int(result.stack[result.top])
elif i == '-':
r = int(result.stack[result.top-1]) - int(result.stack[result.top])
elif i == '*':
r = int(result.stack[result.top - 1]) * int(result.stack[result.top])
elif i == '/':
r = int(result.stack[result.top - 1]) / int(result.stack[result.top])
else:
result.stack.append(i)
result.top += 1
# 用这个条件来判断是否栈中取出了元素
if r != 0:
result.stack.pop()
result.stack.pop()
result.stack.append(r)
result.top -= 1
r = 0
return result.stack[0]
if __name__ == '__main__':
# 测试用例
# 1+2*3+(4*5+6)*3
# 1+2+3+4-5
# (1+2*3+(4*5+6)*3)/5
# (1+4)/5
behind = middle2behind("(1+2*3+(4*5+6)*3)/5")
print("后缀表达式为:{}".format(behind))
result = behindCalculation(behind)
print("计算结果为:{}".format(result))