importrefrom functools importreducedef mul_div(exp): #计算两个数的乘法或者除法
if '*' inexp:
a, b= exp.split('*')return float(a)*float(b)if '/' inexp:
a, b= exp.split('/')return float(a) /float(b)defexp_fmt(exp):while re.search('[+-]{2,}',exp):
exp= exp.replace('--','+')
exp= exp.replace('+-','-')
exp= exp.replace('-+','-')
exp= exp.replace('++','+')returnexpdefremove_addsub(exp):
ret= re.findall('[-+]?\d+(?:\.\d+)?',exp)
res= reduce(lambda a,b:float(a)+float(b),ret)returnresdef remove_muldiv(exp): #计算表达式中的所有的乘除法
whileTrue:
ret= re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp)ifret:
son_exp= ret.group() #3*4 12*5
res =mul_div(son_exp)
exp=exp.replace(son_exp,str(res))else:returnexpdefcal(exp):
res= remove_muldiv(exp) #计算乘除
res = exp_fmt(res) #符号整理
ret = remove_addsub(res) #计算加减
returnretdefmain(exp):
exp= exp.replace(' ', '')whileTrue:
ret= re.search('\([^()]+\)', exp)ifret:
res=cal(ret.group())
exp=exp.replace(ret.group(), str(res))else: returncal(exp)
exp= '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'ret=main(exp)print(ret)