# L1SP语言唯一的语法就是括号要配对,形如(OP P1 P2……),括号内元素由单个空格分割。
# 其中第一个元素OP为操作符,后续元素均为其参数,参数个数取决与操作符类型
# 注意:参数P1 P2也有可能是另外一个嵌套的(OP P1 P2……)
# 当前OP类型为add /sub/mul/div(全小写),分别代表整数的加减乘除法,简单起见,所有的OP的参数个数均为2
#
# 举例:
# 输入:(mul 3 -7)输出:-21
# 输入:(add 1 2)输出:3
# 输入:(sub(mul2 4)(div 9 3)输出:5
# 输入:(div 1 0)输出:error 题目涉及数字均为整数,可能为负
#
#
# 输入:(div 12 (sub 45 45))
# 输出error
#
# 输入:(add 1 (div -7 3))
# 输出:-2
def solve_method(expression):
st = []
res = []
flag = True
i = len(expression) - 1
while i >= 0:
if expression[i] == ")" or expression[i] == " " or expression[i] == "(":
i -= 1
elif expression[i].isalpha():
op = expression[i - 2: i + 1]
st.append(op)
i -= 3
else:
space_index = expression.rfind(" ", 0, i)
if space_index < 0 or ("a" <= expression[space_index + 1] <= "z"):
space_index = expression.rfind("(", 0, i)
num = expression[space_index + 1: i + 1]
st.append(num)
i = space_index
n = len(st)
for j in range(n):
s = st[j]
if s == "add" or s == "sub" or s == "mul" or s == "div":
if len(res) < 2:
return
num2 = res.pop()
num1 = res.pop()
result = 0
if s == "add":
result = num1 + num2
elif s == "sub":
result = num2 - num1
elif s == "mul":
result = num1 * num2
elif s == "div":
if num1 == 0:
flag = False
else:
result = num2 // num1
res.append(result)
else:
res.append(int(s))
if not flag:
print("error")
else:
print(res[-1])
expression = "(add 1 (div -7 3))"
solve_method(expression)
# (div 12 (sub 45 45))
# error