import re

 express = '1 - 2 * ( ( 6 0 -3 0  +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
# 去掉所有的空格
# 找括号,先找括号里面没有括号的最里面的括号
# 先算括号里的乘除,再算括号里的加减 # 计算表达式
def dealwith(express):
if "+-" in express:express.replace("+-","-")
if "+-" in express:express.replace("--","+")
return express def cal_exp_son(exp_son):
# 只用来计算原子型表达式,最小的表达式
if "/" in exp_son:
a,b = exp_son.split("/")
return str(float(a)/float(b))
if "*" in exp_son:
a,b = exp_son.split("*")
return str(float(a) * float(b)) def cal_express_no_bracket(exp):
# 计算没有括号的表达式
# exp 为未经过处理的最内层的带括号的表达式
exp = exp.strip("()")
print(exp)
# 先乘除,后加减
while True:
ret = re.search("\d+\.?\d*[*/]-?\d+\.?\d*",exp)
if ret :
exp_son = ret.group()
ret = cal_exp_son(exp_son)
exp = exp.replace(exp_son,ret) # 将空格去除
new_express = re.sub(" ","",express) #提取括号里面没有其他括号的的表达式
while True:
ret = re.search("\([^()]+\)",new_express)
if ret :
express_no_bracket = ret.group()
ret = cal_express_no_bracket(express_no_bracket)
new_express= new_express.replace(express_no_bracket,ret)
print(new_express)
new_express = dealwith(new_express)
print(new_express)
else:
print("表达式已经没有括号了",new_express)
break

05-08 08:37