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("--","+")returnfunc
def addjian(func):
func= func.strip("()")
ret= re.findall("-?\d*\.?\d+",func)
sum=0
for i inret:
sum+=float(i)returnstr(sum)
def chengchu(func):
func= func.strip("()")while("/"in func or "*" infunc):
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)returnfunc
def comput(formal):
formal= re.sub('\s','',formal)while(re.search('\([^()]*\)',formal)):
print(formal)
ret= re.findall('\([^()]*\)',formal)for i inret:
print("wu kuohao:"+i)
result_chengchu= chengchu(i) if '*'in i or '/' in i elsei#先算乘除
result_addjian= addjian(result_chengchu) if '+'in result_chengchu or '-' in result_chengchu elseresult_chengchu#再算加减
formal= formal.replace(i,result_addjian,1)
formal=zhengli(formal)else:
result_chengchu= chengchu(formal) if '*' in formal or '/' in formal elseformal # 先算乘除
result_addjian= addjian(result_chengchu) if '+' in result_chengchu or '-' in result_chengchu elseresult_chengchu # 再算加减returnresult_addjian
print(comput(formul))