defMUL_DIV (exp):#Calculate multiplication whileTrue:ret= Re.search ('[\d\.] +[\*\/]-? [\d\.] +', exp)ifRet:atom_exp=Ret.group () Res=atom_cal (ATOM_EXP) exp=exp.replace (Atom_exp, res)Else: returnFOMAT_EXP (exp)defFOMAT_EXP (exp):#after calculating the multiplication, the unified symbolExp=exp.replace ('--','+') Exp=exp.replace ('-+','-') Exp=exp.replace ('++','+') Exp=exp.replace ('+-','-') returnadd_sub (exp)defADD_SUB (exp):#calculate add and SubtractRet=re.findall ('[\-\+]? [\d\.] +', exp) exp_sum=0 forIinchRet:exp_sum+=float (i)returnExp_sumdefMain (exp):#The main program, the first calculation in parenthesesExp=exp.replace (' ',"') whileTrue:ret=re.search ('\([^()]+\)', exp)ifRet:inner_bracket=Ret.group () Res=Str (MUL_DIV (inner_bracket)) exp=exp.replace (Inner_bracket, res)Else: Break returnMUL_DIV (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) )'Print(Main (exp))
View Code
Python Re module Implementation calculator