Write a simple calculator in the Python language

Source: Internet
Author: User

If we have such a formula:

1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2))
Idea: The logic should be in parentheses first
And then, outside the brackets,
So we can find out all the equations inside the inner brackets.
Should be "( -40/5)", "(9-2*5/3 + 7/3*99/4*2998 +10 * 568/14)", "( -4*3)", "(16-3*2)", such as
And the parentheses should be the first multiplication method, and then add and subtract
After you have calculated these values, replace them with the calculated values of the original parentheses.
And then looking for no parentheses, if any, continue with the above operation once
After you finish calculating the parentheses
Finally, the result of the subtraction operation is the result of the operation.
See the following code:
ImportRedefatom_cal (exp):if '*' inchExp:#to calculate a single multiplicationA, B = exp.split ('*')        returnSTR (FLOAT (a) *float (b))elif '/' inchExp:#to calculate a single divisionA, B = exp.split ('/')        returnSTR (float (a)/float (b))defFORMAT_EXP (exp):#Problems with symbolsExp = Exp.replace ('--','+') Exp= Exp.replace ('+-','-') Exp= Exp.replace ('-+','-') Exp= Exp.replace ('++','+')    returnExpdefMUL_DIV (exp):#Computational Multiplication Method     whileTrue:ret= Re.search ('\d+ (\.\d+)? [*/]-?\d+ (\.\d+)?', exp)#Match multiplication or division with regular Expressions        ifRet:#if it matches.Atom_exp = Ret.group ()#take this value out.res = atom_cal (atom_exp)#Call the atom_cal calculation aboveExp = Exp.replace (atom_exp,res)#To replace the result of the calculation with the original.        Else:returnExp#if the match is not reached, the multiplication method is calculated and the result of the calculation is returned.defADD_SUB (exp):#calculate add and Subtractret = Re.findall ('[+-]?\d+ (?: \. \d+)?', exp)#use regular expressions to match each signed number in a calculation to return a listExp_sum =0 forIinchRet:exp_sum+ = float (i)#sum each item in the list    returnExp_sumdefCAL (exp):#Calculate subtraction Mixed operationsExp = MUL_DIV (exp)#Call the Mul_div function first to calculate the multiplication methodExp = FORMAT_EXP (exp)#call Format_exp to process the calculation of the symbolExp_sum = ADD_SUB (exp)#Call Add_sub to calculate addition and subtraction    returnExp_sum#float #返回计算结果defMain (exp): Exp= Exp.replace (' ',"')#Delete spaces in a string     whileTrue:ret= Re.search ('\([^()]+\)', exp)#Match parentheses        ifRet:#if it matches.Inner_bracket = Ret.group ()#use Group () to extract the bracketed content that matches tores = str (cal (Inner_bracket))#call Cal () to calculate the contents of parentheses and convert the returned result to a stringExp = Exp.replace (inner_bracket,res)#Replace the contents of the matching parentheses with the results of the calculationExp = FORMAT_EXP (exp)#Working with symbols        Else: Break  #until no parentheses jump out of the loop    returnCAL (exp)#The rest of the content is calculated and then returneds='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) Final result:2776672.6952380957
Addition Operation Explanation: 9+6-9+5+8-6-5
Such a formula we can think of it as A + (+6) + (-9) + (+5) + (+8) + (-6) + (-5)


Write a simple calculator in the Python language

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.