输入为一个算数表达式的字符串。输出它经过计算之后的结果。如果该字符串不满足算数表达式则输出字符串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
s = input() ops = [] nums = [] def check(s): if s.count('(')!=s.count(')'): return False elif '.' in s: return False else: i = s.find(' ') if i!=-1: if s[i+1].isdigit() and s[i-1].isdigit(): return False s = s.strip() for i in range(len(s)): if s[i] in '+-*/': if i-1<0: return False else: if s[i-1] in '+-*/': return False return True def compute(ops, nums): sec = nums.pop() #这是后面的数 fir = nums.pop() op = ops.pop() nums.append(eval(str(fir) + op + str(sec))) if not check(s): print('Error') else: i = 0 while i < len(s): if s[i] == ' ': i+=1 #这里后面要跳过,必须要在这里i+=1 continue elif s[i] in '(+-*/': ops.append(s[i]) elif s[i] == ')': while ops[-1]!='(': compute(ops, nums) ops.pop() if ops and ops[-1] in '+-': #如果最后是类似(3+5)这样的,要先判断ops是否为空才能计算 compute(ops, nums) else: j = i + 1 while j < len(s) and s[j].isdigit(): j+=1 nums.append(s[i:j]) #不需要用for循环,用切片! if ops and ops[-1] in '+-': #ops不空才计算 compute(ops, nums) i = j - 1 #不用i+=1了,已经可以跳到j-1(最后一个数字) i+=1 while len(ops)!=0: compute(ops,nums) if nums: print(nums[0])