通用计算器模板,分为两个栈
一个栈用来保存数字,一个栈用来保存计算符号
计算发生在遇到右括号或者是当前运算符的优先级低于栈内符号的优先级时
注意预处理时需要对负号进行处理,目的是让每个符号的两边都有数字,不在遍历过程中再对负号进行另外的处理,麻烦。
class Solution(object):
def calculate(self,s):
# 重点是栈内运算符的优先级大于等于当前遇到的运算符就可以运算
dic = {"+": 1, "-": 1, "*": 2, "/": 2}
nums = []
ops = []
s = "(" + s.replace(" ", "").replace("(-", "(0-") + ")"
n = len(s)
i = 0
while i < n:
c = s[i]
i += 1
if c.isdigit(): #这一段将字符串转为数字
num = int(c)
while s[i].isdigit():
num = num * 10 + int(s[i])
i += 1
nums.append(num)
elif c == "(":
ops.append(c)
elif c == ")":
while ops and ops[-1] != "(":
self.cacl(nums, ops)
ops.pop()
else: #当前运算符优先级低于前面的
while ops and ops[-1] != "(":
if dic[c] > dic[ops[-1]]:
break
self.cacl(nums, ops)
ops.append(c)
return int(nums.pop())
def cacl(self,nums, ops):
o = ops.pop()
y, x = nums.pop(), nums.pop()
if o == "+":
res = x + y
elif o == "-":
res = x - y
elif o == "*":
res = x * y
else:
res = x / y
nums.append(res)