Using Python to implement a complex formula calculator function

Source: Internet
Author: User
Tags eval

Give a section of the following line, more complex operation formula, write your own code calculation 1-2.99 * ((60.2-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10.5 * 568/14))-( -4*3)/(16-3* 2)  ideas: Step1. Need to check legality first, detect the illegal character step2 with no letters and other non-operations. Format formulas, remove spaces, replace (--,+-,-+,++) with double operators such as (+,-,-,+ Step3. First calculate () the multiplication, add and subtract, and then calculate the last non-contained () multiplication, plus and minus

#Check the legality of the formula, there are no illegal charactersdefCheck (s):if  notS.count ('(') = = S.count (')'):        Print('Please check that parentheses are not closed')    elifRe.findall ('[[Email protected]#$]','s') is  notNone:Print('Please check that the formula contains illegal symbols')    elifRe.findall ('[A-za-z]','s') is  notNone:Print('Please check that the formula contains letters')    elifS >= u'\u4e00'  andS <= u'\u9fa5':        Print('Please check that the formula contains Chinese')#formatting formulas, removing spaces, redefining double symbolsdefformats (s): s= S.replace (' ',"') s= S.replace ('++','+') s= S.replace ('--','+') s= S.replace ('+-|-+','-') s= S.replace ('*+','*') s= S.replace ('/+','/')    returnS
Take the number and the method with the decimal point, 2 kinds of results are the same, pay attention to experience
ret = Re.findall (R ' [\d\.] + ', ' NUMBRT 1.58 ABC 123 ')
Print (ret) # [' 1.58 ', ' 123 ']
ret = Re.findall (' \d\.? \d* ', ' NUMBRT 1.58 ABC 123 ')
Print (ret) # [' 1.58 ', ' 123 ']

defCheng_chu (s):#handling multiplication with a minus signs =formats (s) r= Re.compile (r'[\d\.] +[\*/]-? [\d\.] +')     whileRe.search (R'[\*/]', s): Ma=Re.search (R, s). Group ()#print (MA)Li = Re.findall (r'(-?[ \d\.] +|\*|/)', MA)ifLI[1] = ='*': Result= str (float (li[0]) * FLOAT (li[2]))        Else: Result= str (float (li[0])/float (li[2])) s= S.replace (MA, result, 1)    returnsdefJia_jian (s):#processing add and subtract, becoming an array, full pluss =formats (s) Li= Re.findall (r'([\d\.] +|\+|-)', s) nums=0 forIinchRange (len (LI)):ifLi[i] = ='-': Li[i]='+'Li[i+ 1] = float (li[i + 1]) *-1 forIinchLi:ifi = ='+': I=0 Nums= Nums +float (i)returnStr (nums)defSimple (x):#handle without parentheses.    returnJia_jian (Cheng_chu (x))defJisuan (x):#Handle the parentheses     while '(' inchX:reg= Re.compile (r'\([^\(\)]+\)') Ma=Re.search (Reg, X). Group () result= Simple (ma[1:-1]) x= X.replace (MA, result, 1)    returnSimple (x)
' 1-2.99 * ((60.2-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10.5 * 568/14))-( -4*3)/(16-3*2) ) '. Replace (' ")print(' your results:')  , Jisuan (ss))print('eval calculation result:', eval (ss))

The following test phase is strange:

If Jisuan (ss) = = eval (ss):
Print (' Calculate right, you're great yo @[email protected] ')
Else
Print (' not calculated correctly, please try again! ‘)

# Here is strange, if not str (), direct comparison, it will show ' calculation is incorrect ', is there a decimal point behind it?
If STR (Jisuan (ss)) = = str (eval (ss)):
Print (' Calculate right, you're great yo @[email protected] ')
Else
Print (' not calculated correctly, please try again! ‘)

Ask the big guy to point out.

Using Python to implement a complex formula calculator function

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.