def calculate(s):
ans = 0
num = 0
stack = []
sign = '+'
i = 0
while i < len(s):
if s[i]>= '0' and s[i] <= '9':
num = num*10 + int(s[i])
if s[i] == '(':
l = i
cnt = 1
i += 1
while cnt > 0:
if s[i] == '(':
cnt += 1
elif s[i] == ')':
cnt -= 1
i += 1
num = calculate(s[l+1:i-1])
i -= 1
if i == len(s)-1 or s[i] == '+' or s[i] == '-' or s[i] == '*':
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack[-1] *= num
sign = s[i]
num = 0
i += 1
while stack:
ans += stack.pop()
return ans
测试:
s = "(6+9-2)*6*(7-2*3)-3"
ans = calculate(s)
print(ans)
结果:
75