AcWing 3302. 表达式求值(Python)
原题链接
简单
作者:
习学学
,
2021-03-22 11:14:57
,
所有人可见
,
阅读 996
Python 代码
nums, ops = [], []
prority = {'-': 0, '+': 0, '*': 1, '/': 1}
char = input()
n = len(char)
def eval():
op = ops.pop()
b = nums.pop()
a = nums.pop()
if op == "+": a += b
elif op == "-": a -= b
elif op == "*": a *= b
else: a = int(a / b)
nums.append(a)
i = 0
while i < n:
if char[i].isdigit():
num = 0
while i < n and char[i].isdigit():
num = num * 10 + int(char[i])
i += 1
nums.append(num)
continue
elif char[i] == ')':
while ops[-1] != '(': eval()
ops.pop()
elif char[i] == '(': ops.append('(')
else:
while ops and ops[-1] != '(' and prority[ops[-1]] >= prority[char[i]]: eval()
ops.append(char[i])
i += 1
while ops: eval()
print(nums[-1])