Python implements a calculator function

Source: Internet
Author: User

#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.