Python's calculator

Source: Internet
Author: User

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 _*_

‘‘‘
Created on January 17, 2016
@author: Wang Kai
‘‘‘


‘‘‘
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

The execution process is as follows:
Please evaluate the expression: 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: [' 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.0
After: [' 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*2)]
9-2*5/3+7/3*99/4*2998+10*568/14=173545.880953
After: [' 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.04762
After: [' 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.0
After: [' 1-2* ( -1388337.04762--12.0/(16-3*2)) ']
========== Last calculated end ==========
Before: [' 1-2* ( -1388337.04762--12.0/(16-3*2)) ']
16-3*2=10.0
After: [' 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.84762
After: [' 1-2*-1388335.84762 ']
========== Last calculated end ==========
My calculation results: 2776672.69524
‘‘‘


Import Re,os,sys

def compute_exponent (ARG):
"" "Action Index
:p Aram Expression: expressions
: Return: Calculation results
"""

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

Before, 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):
"" Action multiplication
:p Aram Expression: expressions
: Return: Calculation results
"""

val = arg[0]
Pattern = Re.compile (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)
Elif Len (Content.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)
Elif Len (content.split ('/')) >1:
N1, N2 = Content.split ('/')
Value = Float (n1)/float (N2)
Else
Pass

Before, after = Pattern.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: expressions
: Return: Calculation results
"""
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 ('-', ' & ')
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 = Content.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):
"" Action subtraction
:p Aram Expression: expressions
: Return: Calculation results
"""
INP = [expression,0]

# process an exponent in an expression
Compute_exponent (INP)

# deal with multiplication in an expression
Compute_mul_div (INP)

# Handle the addition and subtraction of an expression
Compute_add_sub (INP)
If Divmod (inp[1],2) [1] = = 1:
result = Float (inp[0])
result = result *-1
Else
result = Float (inp[0])
return result


def exec_bracket (expression):
"" recursively handles the parentheses and calculates
:p Aram Expression: expressions
: return: 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 and return the result of the expression, such as: 2*1-82+444
#if not Re.search (' \ ([\+\-\*\/]*\d+\.*\d*) {2,}\) ', expression):
If not pattern.search (expression):
Final = compute (expression)
Return final
# Gets the first parenthesis that contains 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 (content)-1]

# Calculate, extract the Representation ( -40.0/5), and live the result, namely: -40.0/5=-8.0
RET = COMPUTE (content)

Print ('%s=%s '% (content, ret))

# Concatenation of execution results, [' 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"% (before, ret, after)
Print (' After: ', expression)
Print ("=" *10, ' previous result is ', "=" *10)

# Loop continues the next parenthesis processing operation, this time the carrier is the expression that has been processed, namely:
# [' 1-2* ((60-30+-8.0 * (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)) ']

# so again and again, until the expression no longer contains parentheses
return Exec_bracket (expression)

# Purpose of using __name__:
# The following code executes only if Python index.py is executed
# If someone else imports the module, the following code does not execute
if __name__ = = "__main__":
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 a calculated 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)

Calculator


#!/usr/bin/python27#_*_ coding=utf-8 _*_ "Created on January 17, 2016 @author: Wang Kai" "The calculator idea: 1, recursively look for expressions that contain only numbers and operators, and calculates the result 2, because the integer computation ignores decimals, all numbers are considered floating-point operations, in order to retain 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*2998 +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 over ==========before: [' 1-2* (60-30+-8.0* *2998+10*568/14))-( -4*3)/(16-3*2)) ']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/(16-3*2)) ']========== last calculated over ==========before: [' 1-2* ( -1388337.04762--12.0/) ' 16-3*2 2=10.0after: [' 1-2* ( -1388337.04762--12.0/10.0) ']========== last calculated over ==========before: [' 1-2* ( -1388337.04762--12.0/ 10.0) ']-1388337.04762--12.0/10.0=-1388335.84762after: [' 1-2*-1388335.84762 ']========== last calculation ended ========== 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.compile (R ' \d+\.? \d*[\*\/\%\/\/]+[\+\-]?\d+\.*\d* ') MCH = Pattern.search (val) if not mch:return content = Pattern.search (v    AL). Group () If Len (Content.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) Elif len (Content.split ('% ')) >1:n1, N2 = content.split ('% ') value = float (n1)% float (n2) elif Len (CONTENT.SPL It ('/')) >1:n1, N2 = Content.split ('/') value = float (n1)/float (N2) else:pass before, aft ER = Pattern.split (val, 1) new_str = "%s%s%s"% (before,value,after) arg[0] = New_str Compute_mul_div (ARG) def com Pute_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 ('-', ' & ') 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] # PlaceThe exponential compute_exponent (INP) # in the processing expression multiplication the Compute_mul_div (INP) # Processing expression of the addition and subtraction Compute_add_sub (INP) if di    Vmod (inp[1],2) [1] = = 1:result = Float (inp[0]) result = result *-1 Else:result = float (inp[0]) return resultdef exec_bracket (expression): "" "recursively handles parentheses and evaluates the:p Aram expression: expression: Return: Final calculation result" "" Patte RN = Re.compile (R ' \ (([\+\-\*\/\%\/\/\*\*]*\d+\.*\d*) {2,}\) ') # If there are no parentheses in the expression, call the function that is responsible for the calculation and return the result of the expression, such as: 2*1-82+444 #if n OT Re.search (' \ ([\+\-\*\/]*\d+\.*\d*) {2,}\) ', expression): If not pattern.search (expression): final = COMPUTE (E Xpression) Return final # Gets the first parentheses that contain only numbers/decimals and operators # such as: # [' 1-2* (60-30+ ( -40.0/5) * (9-2*5/3+7/3*99/4*2  998+10*568/14)-( -4*3)/(16-3*2)] # Find out: ( -40.0/5) content = pattern.search (expression). Group () # split expression, i.e.: #      Divide [' 1-2* (60-30+ ( -40.0/5) * (9-2*5/3+7/3*99/4*2998+10*568/14)-( -4*3)/(16-3*2)] # into 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 (content)-1] # Calculate, extract the Representation ( -40.0/5), and live the result, namely: -40.0/5=-8.0 RET = COMPUTE (content) print ('%    s=%s '% (content, ret)) # will perform the 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"% (before, ret, after) print (' After: ', expression) print ("=" *10, ' previous result is ', "=" *10)    # Loop continues the next parenthesis processing operation, this time the carrier is the processed expression, 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 again and again, until the expression is no longer enclosed in parentheses return exec_bracket (expression) # Purpose of using __name__: # Only the following code executes when Python index.py is executed # if someone else                                                     Importing the module, the following code does not execute if __name__ = = "__main__": 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 calculated 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

Python's calculator

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.