Homework:
Use regular expressions and recursion to implement the calculator function.
Realize:
1, the implementation of the calculation of parentheses
2, achieve the index, subtraction and other functions
First, the example illustrates:
This instance wrote a version of itself, but there is still a little bug, example:-2-2 and other computational problems, so finally in the code based on Wu Sir added index, to seek redundancy and other functions.
The calculator idea:
1. Recursively look for expressions that contain only numbers and operators in the expression, and calculate the result
2, because the integer calculation ignores decimals, all numbers are considered floating-point operations, in order to preserve decimals
Use technology:
1. Regular expressions
2. Recursion
Second, flow chart:
Third, the code:
#!/usr/bin/python27#_*_ coding=utf-8 _*_ "" "The calculator idea: 1, recursively look for expressions that contain only numbers and operators, and calculate the result 2, because integer computation ignores decimals, all numbers are considered floating-point To preserve the fractional use of technology: 1, Regular expression 2, the recursive execution process is as follows: ******************** please evaluate the expression: 1-2 * ((60-30 + ( -40.0/5) * (9-2*5/3 + 7/3*99/4*29 98 +10 * 568/14))-( -4*3)/(16-3*2)) ********************before: [' 1-2* (60-30+ ( -40.0/5) * (9-2*5/3+7/3*99/4*2998+10* 568/14))-( -4*3)/(16-3*2)) ']-40.0/5=-8.0after: [' 1-2* (60-30+-8.0* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/( 16-3*2)]========== Last calculated end ==========before: [' 1-2* (60-30+-8.0* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3 *) ']9-2*5/3+7/3*99/4*2998+10*568/14=173545.880953after: [' 1-2* ((60-30+-8.0*173545.880953)-( -4*3)/(16-3*2)) ']= ========= Last calculated end ==========before: [' 1-2* ((60-30+-8.0*173545.880953)-( -4*3)/(16-3*2)) ']60-30+-8.0*173545.880953= -1388337.04762after: [' 1-2* ( -1388337.04762-( -4*3)/(16-3*2) ']========== Last calculated end ==========before: [' 1-2* (- 1388337.04762-( -4*3)/(16-3*2)) ']-4*3=-12.0after: [' 1-2* ( -1388337.04762--12.0/) ']========== Last calculated end ==========before: [' 1-2* ( -1388337.04762--12.0/(16-3*2)) ']16-3*2=10.0after: [' 1-2* (- 1388337.04762--12.0/10.0) ']========== Last calculated end ==========before: [' 1-2* ( -1388337.04762--12.0/10.0) ']-1388337.04762 --12.0/10.0=-1388335.84762after: [' 1-2*-1388335.84762 ']========== last calculated end ========== my results: 2776672.69524 ' Import Re,os,sysdef compute_exponent (ARG): "" "action exponent:p Aram expression: expression: return: Calculation Result" "" val = arg[0] Pattern = Re.compile (R ' \d+\.? \d*[\*]{2}[\+\-]?\d+\.? \d* ') MCH = Pattern.search (val) if not mch:return content = Pattern.search (val). Group () If Len (content . Split (' * * ')) >1:n1, N2 = Content.split (' * * ') value = float (N1) * * Float (n2) Else:pass befo Re, after = Pattern.split (val, 1) new_str = "%s%s%s"% (before,value,after) arg[0] = New_str compute_exponent (arg ) def Compute_mul_div (ARG): "" "Operation multiplication:p Aram expression: expression: return: Calculation Result" "" val = arg[0] Pattern = re.com Pile (R ' \d+\.? \d*[\*\/\%\/\/]+[\+\-]?\d+\.*\d* ') MCH = Pattern.search (val) if not mch:return content = Pattern.search (val ). Group () If Len (Content.split (' * ')) >1:n1, N2 = Content.split (' * ') value = float (n1) * Float (n2) E Lif Len (Content.split ('//)) >1:n1, N2 = Content.split ('//') value = float (n1)//float (n2) elif Len (c Ontent.split ('% ')) >1:n1, N2 = content.split ('% ') value = float (n1)% float (n2) elif Len (content.split (‘/‘)) >1:n1, N2 = Content.split ('/') value = float (n1)/float (N2) Else:pass before, after = Pat Tern.split (Val, 1) new_str = "%s%s%s"% (before,value,after) arg[0] = New_str Compute_mul_div (ARG) def Compute_add _sub (ARG): "" "Operation plus minus:p Aram expression: expression: return: Calculation Result" "" while True:if arg[0].__contains__ (' +-') or arg[0].__contains__ ("+ +") or arg[0].__contains__ ('-+ ') or arg[0].__contains__ ("--"): arg[0] = Arg[0].replace (' +-', '-') Arg[0] = arg[0].replace (' + + ', ' + ') arg[0] = arg[0].replace ('-+ ', '-') arg[0] = Arg[0].replace ('--') , ' + ') else:break if Arg[0].startswith ('-'): arg[1] + = 1 Arg[0] = arg[0].replace ('-', ' & amp; ') Arg[0] = arg[0].replace (' + ', '-') arg[0] = Arg[0].replace (' & ', ' + ') arg[0] = arg[0][1:] val = arg[0] Pattern = Re.compile (R ' \d+\.? \d*[\+\-]{1}\d+\.? \d* ') MCH = Pattern.search (val) if not mch:return content = Pattern.search (val). Group () If Len (content . Split (' + ')) >1:n1, N2 = content.split (' + ') value = float (n1) + float (n2) else:n1, N2 = Conten T.split ('-') value = float (n1)-Float (N2) before, after = Pattern.split (val, 1) new_str = "%s%s%s"% (before , value,after) arg[0] = New_str compute_add_sub (ARG) def compute (expression): "" Operation subtraction:p Aram expression: expression : return: Calculated result "" "INP = [expression,0] # processing expression in exponential compute_exponent (INP# Processing expression multiplication Compute_mul_div (INP) # Processing expression compute_add_sub (INP) if Divmod (inp[1],2) [1] = = 1:r Esult = float (inp[0]) result = result *-1 Else:result = float (inp[0]) return resultdef Exec_bracket ( Expression): "" recursively handles parentheses and computes the:p Aram expression: "Return: The final calculation result" "" pattern = Re.compile (R ' \ ([\+\-\*\/\% \/\/\*\*]*\d+\.*\d*) {2,}\) ') # If no parentheses are already in the expression, call the function that is responsible for the calculation, returning the expression result, such as: 2*1-82+444 #if not Re.search (' \ ([\+\-\*\/]*\d+ \.*\d*) {2,}\) ', expression): If not pattern.search (expression): final = compute (expression) return final # get the first parentheses with only numbers/decimals and operators # such as: # [' 1-2* (60-30+ ( -40.0/5) * (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2) '] # Find out: ( -40.0/5) content = pattern.search (expression). Group () # split expression, i.e.: # will [' 1-2* (60-30+ ( -40.0/5) * (9-2* 5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)) '] # split the three parts: [' 1-2* ((60-30+ ( -40.0/5) * (9-2*5/3+7/3*99/4*2998+10* 568/14))-( -4*3)/(16-3*2))'] before, nothing, after = pattern.split (expression, 1) print (' Before: ', expression) content = Content[1:len (cont ENT)-1] # Calculate, extract the Representation ( -40.0/5), and live the result, i.e.: -40.0/5=-8.0 ret = COMPUTE (content) print ('%s=%s '% (content, ret)) # will Execute Result stitching, [' 1-2* ((60-30+ ( -8.0 * (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)) ' expression = '%s%s%s '% (befor E, ret, after) print (' After: ', expression) print ("=" *10, ' previous result is ', "=" *10) # Loop continues the next parenthesis processing operation, the current carrier is a table that has been processed Reach, i.e.: # [' 1-2* ((60-30+-8.0 * (9-2*5/3+7/3*99/4*2998+10*568/14)-( -4*3)/(16-3*2)) '] # so the cycle is done until the expression no longer contains parentheses in the RE Turn exec_bracket (expression) # Purpose of using __name__: # The following code executes only when Python index.py is executed # If someone else imports the module, the following code does not execute if __name__ = = "__m ain__ ": flag = True Os.system (' Clear ') # # #清屏 # # print (' \n==== ============================================================ ') print (' \033[33m Welcome calculator: \033[0m ') print (' \n======= ========================================================= ') While flag:calculate_input = Raw_input (' \033[32m Please enter the evaluated expression | (exit: Q) \033[0m ') Calculate_input = re.sub (' \s* ', ' ", Calculate_input) If Len (calculate_input) = = 0: Continue elif Calculate_input = = ' Q ': Sys.exit (' Exit program ') elif re.search (' [^0-9\.\-\+\*\/\%\/\/\*\*\ (\)] ', calculate_input): print (' \033[31m input error, please reenter!!! \033[0m ') Else:result = Exec_bracket (calculate_input) print (' The expression result is%s '% Result
Four, for python2.7 and python3.4 not too big difference, so only need a version can.
Python Programming Calculator