Python calculator (fourth day)

Source: Internet
Author: User

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

Python calculator (fourth day)

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.