Python Learning Regular Expression Implementation Calculator algorithm detailed

Source: Internet
Author: User

Regular expression is one of the most commonly used in Python development, this article and we share is the Python development using regular expressions to implement the calculator algorithm related content, together look at it, I hope to everyoneLearn Pythonhelpful.
(1) Do not use Eval () and other systems to bring the calculation method
(2) Implementation of four mixed operation, bracket precedence resolution
Ideas:
1, string preprocessing, all spaces are removed
2, to determine whether there is a parenthesis operation, if there is a 3rd step, if not exist directly into the 4th step
3, using regular expressions to get the arithmetic expression in the bottom bracket
4. Preprocess The arithmetic expression: when the expression starts with a negative number, precede the expression with a 0 -
5, using Re.split (), Re.findall () method, through the addition and subtraction of symbols, the arithmetic is divided into multiplication arithmetic and numbers, and retain the corresponding position subscript.
6, using the Re.split (), Re.findall () method, through the multiplication symbol, the multiplication is split into multiplication symbols and numbers, and then calculated, and return the value.
7. Restore the expression by Re.split (), Re.findall () reserved subscript position.
8. After all multiplication operations are completed, the add and subtract operations are returned.
9. After the addition and subtraction operations are completed, the return expression is substituted.
10, through the recursive function, complete all the parentheses after the operation. All operations can be completed at the end of the arithmetic.
Note: In the process, the processing of negative numbers has three main points: when negative numbers appear at the beginning of an expression, there are subtraction before negative numbers, negative numbers exist in the multiplication style, and do not begin with the expression.
(1) When negative numbers appear at the beginning of an expression: precede with a 0
(2) Negative number is preceded by subtraction: a symbol check replacement is required once each operation has been completed
(3) negative number in the multiplication style and not at the beginning of the expression: move the minus sign to the beginning of the expression
#!/usr/bin/env python#-*-coding:utf-8-*-# Authorang
Import re
def update_formula (calc_list,calc_operator_list):
# re-grouping with the symbol list by splitting the list of expressions
For Index,item in Enumerate (calc_list):
If Index = = 0:
formula = Item
elif Index! = 0:
Formula + = Calc_operator_list[index-1] + Item
return Formula
def negative_start_issue (formula):
#处理负数在括号内表达式开头的情形
calc_list = Re.split ("[+ +]", formula) #通过 +-symbol separates individual multiplication operations
calc_operator_list = Re.findall ("[+-]", formula)
For Index,item in Enumerate (calc_list):
If Index = = 0 and item = = ': # Handle the minus sign at the beginning of the problem
Calc_list[index] = ' 0 '
Else:
Calc_list[index] = Item.strip ()
formula = Update_formula (calc_list,calc_operator_list)
return Formula
def deal_unusual_issue (formula):
# double plus minus symbol processing
formula = Formula.replace ("", "") #去掉空格
formula = Formula.replace ("+ +", "+")
formula = Formula.replace ("+-", "-")
formula = Formula.replace ("-+", "-")
formula = Formula.replace ("--", "+")
return Formula
def deal_negative_issue (formula):
# Dealing with the calculation of negative numbers in multiplication operations (two cases in both front and back positions)
# 1. Negative number in the rear
m = Re.search ("[0-9]+[.] *[0-9]*[*|/][-][0-9]+[.] *[0-9]* ", formula)
# minus_pre = Re.search ("[0-9]+[.] *[0-9]*[*|/][-][0-9]+[.] *[0-9]* ", formula). Group ()
# Note the necessary items that match the non-essential items, such as: "[0-9]+[.] [0-9]+[*|/][-][0-9]+[.] [0-9]+] mistakenly considers non-essential items as necessary.
if M:
Minus_pre = M.group ()
Minus_pro = "-" +minus_pre.replace ("-", "" ")
formula = Formula.replace (Minus_pre,minus_pro)
if "*" in formula or "/-" in formula:
return Deal_negative_issue (Formula)
# 2. Negative number in front
formula = deal_unusual_issue (Formula)
return Formula
def multiply_divide (formula):
# Print ("[%s]"%formula,formula)
# multiplication Calculation
calc_list = Re.split ("[*/]", formula)
operator_list = Re.findall ("[*/]", formula) # Separates multiplication Sign division sign by list
# Print ("Sub_calc_list:", sub_calc_list)
# Print ("Sub_operator_list:", sub_operator_list)
res = 0
for Index2, I in Enumerate (calc_list):
if Index2 = = 0:
res = float (i)
Else:
if operator_list[index2-1] = = ' * ': # Judging by the index in sub_operator_list whether it is addition or subtraction,
Res *= Float (i)
elif operator_list[index2-1] = = '/':
Res/= Float (i)
return res
def add_abstract (formula):
# Add and subtract calculation
# 1. Start position negative number processing
formula = negative_start_issue (Formula)
# 2. Double plus minus symbol processing
formula = deal_unusual_issue (Formula)
# 3. Add and subtract logical operations
calc_list = Re.split ("[+-]", formula)
operator_list = Re.findall ("[+-]", formula)
res = 0
for index, I in Enumerate (calc_list):
If Index = = 0:
res = float (i)
Else:
if operator_list[index-1] = = ' + ':
res + = float (i)
elif operator_list[index-1] = = '-':
Res-= float (i)
return res
"""
Four mixed operation main function
"" " def elementary_arithmetic (formula):
# Negative Processing
formula = negative_start_issue (Formula)
formula = deal_negative_issue (Formula)
# multiplication Operations
calc_list = Re.split ("[+ +]", formula) # separates each multiplication operation with the-+ symbol
calc_operator_list = Re.findall ("[+-]", formula)
for INDEX1, item in Enumerate (calc_list):
Calc_list[index1] = str (multiply_divide (item)) #数据类型的强制转换!!!
formula = Update_formula (calc_list,calc_operator_list)
# Add and subtract operations
formula = Add_abstract (Formula)
return Formula
"""
parentheses Operation
"""
def calculator (formula):
#数据预处理
formula = Formula.replace ("", "" ")
m = Re.search ("\ ([^ ()]*\)", formula)
# Determine if parentheses are required
if M:
# parentheses Operation
# Extract the minimum parenthesis formula, calculate the result, and return.
subformula = M.group (). Strip ("()") # Peel out the parentheses
print ("Subformula:", Subformula,type (subformula))
subres = elementary_arithmetic (subformula) # call four mixed operation main function
print ("Subres:", Subres)
formula = Formula.replace (M.group (), str (subres))
Print ("Updated formula:", Formula)
if "(" in formula:
return Calculator (formula)
Else:
print ("Formula result:", formula)
# After removing all parentheses, it may appear: 1-2*-312.8
formula = elementary_arithmetic (Formula)
return Formula
Else:
return elementary_arithmetic (Formula)
# The following is the test code:
formula = "1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*9/4*28 +10 * 56/14))-( -4*3)/(16-3*2))"
print ("%s ="%formula,calculator (formula))


Source: Network

Python Learning Regular Expression Implementation Calculator algorithm detailed

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.