题目描述
代码实现
# coding:utf-8
# 仿LISP运算
# https://www.nowcoder.com/discuss/360006188531032064?sourceSSR=search
import sys
try:
while True:
line = sys.stdin.readline().replace('(', '( ').replace(')', ' )').strip().split(' ')
if line == '':
break
stack = []
op = []
error_flag = False
def cal(operation, p1, p2):
res = 0
if operation == 'add':
res = p1 + p2
if operation == 'sub':
res = p1 - p2
if operation == 'mul':
res = p1 * p2
if operation == 'div':
if p2 == 0:
global error_flag
error_flag = True
else:
res = p1 // p2
return res
for i in range(len(line)):
if line[i] == '(':
stack.append(line[i])
elif line[i] == ')':
if not stack:
error_flag = True
break
stack.pop()
p2 = int(op.pop())
p1 = int(op.pop())
operation = op.pop()
res = cal(operation, p1, p2)
op.append(res)
else:
op.append(line[i])
if error_flag:
break
if error_flag:
print("error")
else:
print(res)
except:
print('error')