1. First write the regular expression of the expression (add minus, multiplication, multiply negative, except negative, match parentheses innermost)
L1_expression = Re.compile (R ' (-?\d+) (\.\d+)? [ -+] (-?\d+) (\.\d+)? ') #匹配加减的正则表达式l2_expression = Re.compile (R ' (-?\d+) (\.\d+)? [ /*] (-?\d+) (\.\d+)? ') #匹配乘除的正则表达式l3_expression = Re.compile (R ' (-?\d+) (\.\d+)? \*-(-?\d+) (\.\d+)? ') #匹配乘负数的正则表达式l4_expression = Re.compile (R ' (-?\d+) (\.\d+)?/-(-?\d+) (\.\d+)? ') #匹配除负数的正则表达式l5_expression = re.compile (R ' \ ([^ ()]*\) ') #匹配包含括号的正则表达式
Compile () compiles the regular expression pattern, returning the pattern of an object
When matching numbers according to an expression, you first have to determine what number the first number is when you match the formula of the expression (for example: positive and negative floating-point numbers ' 0.1 ' or '-0.1 ', positive and negative integer ' 1 ' or '-1 ',)
2. Then write the method of calculating the formula (Formula Computing: Formula calculation, Operator: operator, multiple: multiple, parentheses: parentheses)
First, write a symbol that matches the calculation, which is used to process the input expression.
def one_operator (string): if String.count (' + ') = = 1: return str (float (string[:string.find (' + ')]) + float ( String[string.find (' + ') + 1:])) #匹配加号前面和加号加字符串后面的算式 elif string[1:].count ('-') = = 1: #string [1:] To match a string that starts with a negative number return str (float (string[:string.find ('-', 1)])-Float (string[string.find ('-', 1) + 1:])) # Start looking from the first element (prevent the direct negative from starting with a match) elif string.count (' * ') = = 1: return str (float (string[:string.find (' *)]) * FLOAT ( String[string.find (' * ') + 1:])) #匹配乘法然后用字符串拼接起来 elif string.count ('/') = = 1: return str (FLOAT (string[ : String.find ('/')])/float (string[string.find ('/') + 1:])) #匹配除法用字符串拼接起来
In defining a matching calculation operation, the parentheses are not matched to calculate the processed calculation.
def multiple_operator (String): If String.count (' + ') + string.count (' * ') + string.count ('/') = = 0 and String[1:].find ('- ') < 0: #如果找到 +/* equals 0 elements and starts from the first element no-no-no-no-no-no-strings return string Elif string. Count (' +-') + string.count ('---') + string.count (' * * ') + string.count ('/-') = 0: #如果算是里面有运算负数的话执行以下步骤 string = String.Replace ("+-", '-') #以数学运算的方式转换运算符 "+ +" replaced by '-' string = String.Replace ("--", ' + ') if string . COUNT (' * * ')! = 0: #处理乘负数 string = String.Replace (L3_expression.search (String). Group (), '-' +l3_expression.search (string). Group (). R Eplace (' * * ', ' * ')) #乘负先计算出结果然后转换为负数 if String.count ('/-')! = 0: #处理除负数 string = String.Replace (L4_expression.search (String). Group (), '-' +l4_e Xpression.search (String). Group (). Replace ('/-', ' * ')) return Multiple_operator (String) #最后用递归的方式把结果传给自己直到把所有的负数转换为可执行的运算式 elif String.cou NT (' * ') + string.count ('/')! = 0: # Handles multiplication ret = L2_expression.search (string). Group () #调用re处理乘除的表达式, assign the result to a new variable string = String.Replace (ret, one_operator (ret)) #然后把结果和放到符号处理的函数里的结果 (re-stitching formula) change return multiple_o Perator (String) #用递归的方式 Until the results of the multiplication expression are fully calculated, Eli.F string.count (' + ')! = 0 or String.count ('-')! = 0: #处理加减 ret = L1_expression.search (string). Group () #调用re处理加减的表达式, assign the computed result to a new variable string = String.Replace (ret, one_operator (ret)) #然后把结果放入到符号处理的函数里的结果 (re-piglet formula) convert return Multiple_operator (String) #最后用递归的方式把所有的加减的结果完全计算出来
Finally, you need to define a calculation that matches the parentheses (the calculation of the innermost brackets is calculated first, and pushed outwards, until there is no parenthesis).
def parentheses (string): If String.find (' (') = =-1: #如果表达式没有括号 return Multiple_operator (String) # Call the function of the calculation expression to process its result else: ret = L5_expression.search (string). Group () #处理括号里面的表达式 (now just take the innermost brackets out) Assign to a new variable string = String.Replace (Ret,multiple_operator (ret[1:-1))) #然后把新的表达式和最新的表达式的运算结果转换一下 ( Calculate the result of the innermost parenthesis) return parentheses (string) #最后继续匹配括号, knowing that all brackets are taken out and the results taken out.
3. Wait until the function is complete to debug the calling function and the expression that evaluates the formula
Stat_print = Print ("calculator version 3.0 \ n Input ' q ' exit program") while True: formula_computing = input ("Enter calculation formula:") formula_computing = Formula_computing.replace ("", "") if formula_computing = = "Q": print (' Thank you use ~ ') break Else: Print ("Calculated result:", parentheses (formula_computing))
Python Basics "11th article": A calculator for regular expressions