测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
# BV1xp4y1r7rc 中缀表达式转后缀表达式 # BV1iz4y1k7Ct 后缀表达式的计算方式 calc = { "+": "1", "-": "1", "*": "2", "/": "2" } def trans(exp): res = [] symbol = [] for e in exp: if(e in calc): while(len(symbol) > 0 and calc[e] <= calc[symbol[-1]]): res.append(symbol.pop()) symbol.append(e) else: res.append(e) while(len(symbol) != 0): res.append(symbol.pop()) return res def calc_exp(exp): stack = [] for e in exp: if(e not in calc): stack.append(e) else: b = float(stack.pop()) a = float(stack.pop()) result = 0 if(e == "+"): result = a+b elif(e == "-"): result = a-b elif(e == "*"): result = a*b elif(e == "/"): result = a/b else: raise "Error calc symbol" stack.append(result) return stack[-1] try: while True: exp = input().split() if(exp == 0): break new_exp = trans(exp) res = calc_exp(new_exp) print("%.2f" % res) except: pass
python 可以直接 eval 不过这里主要是学习思想。
if __name__ =='__main__': while True: try: funs=input() n=len(funs) sign='+' d=0 res=[0] for i in range(n): if funs[i]>='0': d=d*10+int(funs[i]) if funs[i]<'0' and funs[i]!=' ' or i==n-1: if sign=='+': res.append(d) elif sign=='-': res.append(-1*d) elif sign=='*': res.append(res.pop()*d) elif sign=='/': res.append(res.pop()/d) d=0 sign=funs[i] print('%.2f'%sum(res)) except: break