1 import re 2 3 4 def strip_operate(exp): # 合并多余的操作符 5 exp = exp.replace("+-", "-") 6 exp = exp.replace("--", "+") 7 return exp 8 9 10 def cal_exp_son(exp_son): # 计算两数的乘除 11 if "/" in exp_son: 12 a, b = exp_son.split("/") 13 return str(float(a)/float(b)) 14 elif "*" in exp_son: 15 a, b = exp_son.split("*") 16 return str(float(a)*float(b)) 17 18 19 def cal_no_bracket(exp): # 计算一个里面已经没有括号的式子 20 exp = exp.strip("()") 21 while True: 22 ret1 = re.search(r"\d+\.?\d*[/*]-?\d+\.?\d*", exp) 23 if ret1: # 先乘除 24 exp_son = ret1.group() 25 ret2 =cal_exp_son(exp_son) 26 exp = exp.replace(exp_son, ret2) 27 exp = strip_operate(exp) 28 else: # 后加减 29 ret4 = re.findall(r"-?\d+\.?\d*", exp) 30 sum1 = 0 31 for i in ret4: 32 sum1 += float(i) 33 return str(sum1) 34 35 36 def main_1(express): 37 while True: 38 ret = re.search(r"\([^()]+\)", express) 39 if ret: 40 express_no_bracket = ret.group() 41 ret3 = cal_no_bracket(express_no_bracket) 42 express = express.replace(express_no_bracket, ret3) 43 express = strip_operate(express) 44 else: 45 ret4 = cal_no_bracket(express) 46 return ret4 47 48 49 express = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' 50 express = express.replace(" ", "") 51 ret5 = main_1(express) 52 print(ret5)