#s = ' 1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2)) '#第一步Step Implementation ("2-1*-22+3-10/-5") #1. Implement a multiplication method two-phase multiplication/ Division #2. Implement an Add/subtract 22 Add/Subtract #3. Replace the result of the calculation with the original expression #4. Replace the symbol with the whole expression after completion #5. Five functions: Calculate atom_cal () format () Mul_div () add_sub () Cal ()#第二步the parentheses are computed in parentheses.ImportRedefFormat (exp): Exp= Exp.replace ("-+","-") Exp= Exp.replace ("+-","-") Exp= Exp.replace ("--","+") Exp= Exp.replace ("++","+") returnExpdefatom_cal (exp):if "*" inchexp:a,b= Exp.split ("*") returnSTR (FLOAT (a) *float (b))elif "/" inchExp:a, b= Exp.split ("/") returnSTR (float (a)/float (b))defMUL_DIV (exp): whileTrue:ret= Re.search ("\d+ (\.\d+)? [*/]-?\d+ (\.\d+)?", exp)#get multiplication expression #从左到右拿结果, can't get back to none ifRet:atom_exp=Ret.group () Res=atom_cal (ATOM_EXP)#print (atom_exp,res)Exp =exp.replace (atom_exp,res)Else: returnExpdefadd_sub (exp): RET= Re.findall ("[+-]?\d+ (?: \. \d+)?", exp)#Take out the numbers and symbols in front of the numbers FindAll returns a list to find all itemsExp_sum =0 forIinchRet:exp_sum= Exp_sum + float (i)#The string is taken out. returnExp_sumdefCAL (exp): Exp=MUL_DIV (exp) Exp=Format (exp) exp_sum=add_sub (exp)returnExp_sumdefMain (exp): Exp= Exp.replace (" ","") whileTrue:ret= Re.search ("\([^()]+\)", exp)ifRet:inner_bracket=Ret.group () Res=Str (CAL (Inner_bracket)) exp=exp.replace (inner_bracket,res) exp=Format (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)
Python implements a calculator function