输入为一个算数表达式的字符串。输出它经过计算之后的结果。如果该字符串不满足算数表达式则输出字符串Error。
注意:
0. 输入中的数只有非负整数。小数、负数等均需要输出Error。
1. 需要支持运算符加、减、乘以及括号。
2. 运算符的优先级为:括号>加=减>乘。
3. 支持数与操作符、操作符与操作符之间有任意空格。
3. 输入和运算过程中不需要考虑整数溢出,用32位的int即可。
输入1:123
输入2:1 23
输入3:1 + 2 * 3
输入4:1+(2*3)
输出1:123
输出2:Error
输出3:9
输出4:7
1 + 2 * 3 - (4*5)
-51
1 + 2 * 3 - (4*5) => 1 + 2 * 3 - 20 => 3 * 3 - 20 => 3 * -17 => -51
import sys
def prior(s):
if s in ['+','-']:
return 1
if s in ['*','/']:
return 0
if s in ['(']:
return -1
def RPN(lst):
n=len(lst)
if n==1:
return int(lst[0])
res=0
cal=[]
for i in range(n):
if lst[i] in ['+','-','*','/']:
b=cal.pop()
a=cal.pop()
sign=lst[i]
if sign == '+':
res = int(a) + int(b)
elif sign == '-':
res = int(a) - int(b)
elif sign == '*':
res = int(a) * int(b)
elif sign == '/':
res = int(a) / int(b)
cal.append(res)
else:
cal.append(int(lst[i]))
return cal.pop()
def solve(s):
vector=[]
stack=[]
n=len(s)
temp=''
for i in range(n):
if s[i]==' ':
continue
if s[i].isdigit():
temp+=s[i]
if i==n-1:
vector.append(temp)
else:
if temp.isdigit():
vector.append(temp)
temp=''
if len(stack)==0:
stack.append(s[i])
else:
if s[i]=='(' :
stack.append(s[i])
elif s[i]==')':
while len(stack)>0 and stack[-1]!='(':
vector.append(stack.pop())
stack.pop()
elif prior(s[i])>prior(stack[-1]):
stack.append(s[i])
elif prior(s[i])<=prior(stack[-1]):
while len(stack)>0 and prior(s[i])<=prior(stack[-1]):
vector.append(stack.pop())
stack.append(s[i])
while len(stack)>0:
vector.append(stack.pop())
return vector
def check(s):
n=len(s[:-1])
flag=''
for i in range(n):
if s[i]>='0' and s[i]<='9':
flag+='0'
elif s[i]==' ':
flag+='1'
elif s[i] in '+-*/':
flag+='2'
elif s[i] in'()':
flag+='3'
else:
flag+='4'
return flag
if __name__ =='__main__':
for line in sys.stdin:
if line.count('(')!=line.count(')'):
print('Error')
else:
if '010' in check(line):
print('Error')
elif '22' in check(line):
print('Error')
else:
res=solve(line[:-1])
ans=RPN(res)
print(ans)