import re formul=`1 - 2 *( (6 0- 30+(0-40/5) * (9-2* 5/3 +7 /3*99/4*2998 +10 *568/14)) - (-4*3) / (16-3*2))` def zhengli(func): func = func.replace("+-","-").replace("--","+") return func def addjian(func): func = func.strip("()") ret = re.findall("-?d*.?d+",func) sum=0 for i in ret: sum +=float(i) return str(sum) def chengchu(func): func = func.strip("()") while("/"in func or "*" in func): ret = re.search(`d*.?d+[*/]-?d*.?d`,func).group() digital = re.split(`([*/])`,ret) #加個括號是為了優先順序的原因,保留非數字 result = str(float(digital[0])*float(digital[2])) if digital[1] == `*` else str(float(digital[0])/float(digital[2])) func = func.replace(ret,result,1) func = zhengli(func) return func def comput(formal): formal = re.sub(`s`,``,formal) while(re.search(`([^()]*)`,formal)): print(formal) ret = re.findall(`([^()]*)`,formal) for i in ret: print("wu kuohao:"+i) result_chengchu = chengchu(i) if `*`in i or `/` in i else i#先算乘除 result_addjian = addjian(result_chengchu) if `+`in result_chengchu or `-` in result_chengchu else result_chengchu#再算加減 formal = formal.replace(i,result_addjian,1) formal = zhengli(formal) else: result_chengchu = chengchu(formal) if `*` in formal or `/` in formal else formal # 先算乘除 result_addjian = addjian(result_chengchu) if `+` in result_chengchu or `-` in result_chengchu else result_chengchu # 再算加減 return result_addjian print(comput(formul))