SoFunction
Updated on 2024-11-12

Python using regular expressions to implement the calculator algorithm idea analysis

(1) Do not use the system's own calculation methods, such as eval()

(2) Realization of mixed quadratic operations, bracket priority parsing

Thoughts:

1, string preprocessing, will remove all spaces

2, to determine the existence of parentheses operation, if there is a step 3, if there is no direct access to step 4

3, the use of regular expressions to obtain the bottom brackets within the four regular expressions

4, the four regular expressions for preprocessing: the beginning of the expression has a negative number, add a 0 in front of the expression

5. Split the four operations into multiplication and division equations and numbers by adding and subtracting symbols and retaining the corresponding positional subscripts, using the () and () methods.

6, the use of (), () method, through the multiplication and division symbols, the multiplication and division equation is split into the multiplication and division symbols and numbers, and then calculate and return the value.

7, through (), () preserved subscript position, the expression will be reduced.

8. After completing all multiplication and division operations, return for addition and subtraction operations.

9. After completing the addition and subtraction operations, the expression is returned for substitution.

10, through the recursive function, after completing all the bracket operations. Finally, you can complete all the operations by completing one more quadratic operation.

Note: There are three main points in the process for handling negative numbers: when the negative number appears at the beginning of the expression, when there is a subtraction in front of the negative number, and when there is a negative number in the multiplication and division equation and not at the beginning of the expression.

(1) When a negative number appears at the beginning of an expression: add a 0 in front of it.

(2) Subtraction exists in front of negative numbers: a sign-checking substitution is required after each completion of an operation

(3) There is a negative number in the multiplication and division equation that is not at the beginning of the expression: move the negative sign to the very beginning of the expression.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Dang
import re
def update_formula(calc_list,calc_operator_list):
  # Recombine the list of expressions with the list of symbols by splitting them up
  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):
  # Handling of negative numbers at the beginning of bracketed expressions
  calc_list = ("[+-]",formula)  # Separate individual multiplication and division operations by the +- sign
  calc_operator_list = ("[+-]",formula)
  for index,item in enumerate(calc_list):
    if index == 0 and item == '':  # Handle the negative sign at the beginning
      calc_list[index] = '0'
    else:
      calc_list[index] = ()
  formula = update_formula(calc_list,calc_operator_list)
  return formula
def deal_unusual_issue(formula):
  # Double plus and minus symbol handling
  formula = (" ","") # Remove the spaces
  formula = ("++","+")
  formula = ("+-", "-")
  formula = ("-+", "-")
  formula = ("--", "+")
  return formula
def deal_negative_issue(formula):
  # Tackle the problem of counting negative numbers in multiplication and division (in both forward and backward positions)
  # 1. Negative numbers follow
  m = ("[0-9]+[.]*[0-9]*[*|/][-][0-9]+[.]*[0-9]*",formula)
 # minus_pre = ("[0-9]+[.]*[0-9]*[*|/][-][0-9]+[.]*[0-9]*",formula).group()
  # Note the essential vs. non-essential terms of the match, e.g. "[0-9]+[...] [0-9]+[*|/][-][0-9]+[.]" mistakenly matches a non-essential term. [0-9]+" mistakenly treats a non-essential term as an essential term.
  if m:
    minus_pre = ()
    minus_pro = "-"+minus_pre.replace("-","")
    formula = (minus_pre,minus_pro)
  if "*-" in formula or "/-" in formula:
    return deal_negative_issue(formula)
  # 2. Negative numbers come first
  formula = deal_unusual_issue(formula)
  return formula
def multiply_divide(formula):
  # print("[%s]"%formula,formula)
  # Multiply and divide
  calc_list = ("[*/]", formula)
  operator_list = ("[*/]", formula) # Separate multiplication and division signs by a 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] == '*': # Determine whether it's an addition or a subtraction by the index in the sub_operator_list.
        res *= float(i)
      elif operator_list[index2 - 1] == '/':
        res /= float(i)
  return res
def add_abstract(formula):
  # Addition and subtraction calculations
  # 1. Handling of negative numbers in the opening position
  formula = negative_start_issue(formula)
  # 2. Double plus and minus symbol handling
  formula = deal_unusual_issue(formula)
  # 3. Add and subtract logical operations
  calc_list = ("[+-]", formula)
  operator_list = ("[+-]", 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
"""

Mixed Quadratic Main Functions

"""def elementary_arithmetic(formula):
  # Negative number handling
  formula = negative_start_issue(formula)
  formula = deal_negative_issue(formula)
  # Multiply and divide
  calc_list = ("[+-]",formula)  # Separate individual multiplication and division operations by the +- sign
  calc_operator_list = ("[+-]",formula)
  for index1, item in enumerate(calc_list):
    calc_list[index1] = str(multiply_divide(item)) #Forced conversions of data types!!!!
  formula = update_formula(calc_list,calc_operator_list)
  # Addition and subtraction
  formula = add_abstract(formula)
  return formula
"""
Parentheses operations
"""
def calculator(formula):
  # Data preprocessing
  formula = (" ","")
  m = ("\([^()]*\)",formula)
  # Determine if bracketing is required
  if m:
    # Parenthesized operations
    # Extract the minimum bracket operator, compute the result, and return it.
    subformula = ().strip("()") # Strip out the brackets that you find
    print("subformula:",subformula,type(subformula))
    subres = elementary_arithmetic(subformula) # Calling the main quadratic arithmetic function
    print("subres:",subres)
    formula = ((), str(subres))
    print("updated formula:",formula)
    if "(" in formula:
      return calculator(formula)
    else:
      print("formula result:",formula)
    # Possible after removing all brackets: 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))

summarize

The above is a small introduction to Python using regular expressions to implement the calculator algorithm, I hope to help you, if you have any questions please leave me a message, I will reply to you in time. Here also thank you very much for your support of my website!