ImportRedefatom_cal (exp): # Calculate Multiplication Methodif '*' inchexp:a,b= Exp.split ('*') returnSTR (FLOAT (a) *float (b))elif '/' inchExp:a, b= Exp.split ('/') returnSTR (float (a)/float (b))defFORMAT_EXP (exp): # Formatting symbols exp= Exp.replace ('--','+') Exp= Exp.replace ('+-','-') Exp= Exp.replace ('-+','-') Exp= Exp.replace ('++','+') returnExpdefMUL_DIV (exp): # multiplication method for finding incoming strings whileTrue:ret= Re.search ('\d+ (\.\d+)? [*/]-?\d+ (\.\d+)?', exp)ifRet:atom_exp=Ret.group () Res=atom_cal (ATOM_EXP) exp=exp.replace (atom_exp,res)Else:returnExpdefadd_sub (exp): # Calculate plus subtract ret= Re.findall ('[+-]?\d+ (?: \. \d+)?', exp) exp_sum=0 forIinchRet:exp_sum+=float (i)returnExp_sumdefCAL (exp): Exp=MUL_DIV (exp) Exp=FORMAT_EXP (exp) exp_sum=add_sub (exp)returnExp_sum#floatdefMain (exp): Exp= Exp.replace (' ',"') # Go to space whileTrue:ret= Re.search ('\([^()]+\)', exp) # Find the contents in the inner bracketsifRet:inner_bracket=Ret.group () Res=Str (CAL (Inner_bracket)) exp=exp.replace (inner_bracket,res) exp=FORMAT_EXP (exp)Else: Break returnCAL (exp) s='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 (s)Print(Ret,type (ret))
Implement a calculator with Python