Package: mathematical-expression-py
mathematical-expression切换至中文文档introduceThis framework is an effective tool for mathematical formula analysis. It can analyze mathematical formulas including
nested functions, including functions, and step accumulation of series. The return value is a numerical result object.
At the same time, it can also be used for comparison operations. When comparing again, the return value is a Boolean
result object.pip Get Commandpipinstallmathematical_expression_pyFrameworkUse mathematical_ Expression packageAfter version 1.2, the use of mathematical is supported_ The expression package obtains various computing components to
reduce the amount of code and the difficulty of library calls.# import mathematical expression parsing libraryimportmathematical_expressionasmathematical# Build two expressions to be evaluateds1,s2="1 + 20 - 2 + 4","1 + 20 - (2 + 4)"# Obtaining an expression evaluation component without parentheses through the libraryprefixExpressionOperation=mathematical.prefixExpressionOperation.get_instance("prefixExpressionOperation")# Obtain the bracketed expression calculation component through the librarybracketsCalculation2=mathematical.bracketsCalculation2.get_instance("bracketsCalculation2")# Another way is to get the calculation component object, which is more similar to the writing method in Java# bracketsCalculation2 = mathematical.get_instance(mathematical.booleanCalculation2, "bracketsCalculation2")# Pass the first formula to the parenthesis expression calculation component Check and calculate the formula can also be passed to the parenthesis expression calculationprefixExpressionOperation.check(s1)calculation=prefixExpressionOperation.calculation(s1)# Print the calculation result of the first expressionprint("计算层数："+str(calculation.get_result_layers())+"\n计算结果："+str(calculation.get_result())+"\n计算来源："+calculation.get_calculation_source_name())# Pass the second formula to the bracketed expression calculation component for check and calculationbracketsCalculation2.check(s2)calculation2=bracketsCalculation2.calculation(s2)# Print the calculation result of the second expressionprint("计算层数："+str(calculation2.get_result_layers())+"\n计算结果："+str(calculation2.get_result())+"\n计算来源："+calculation2.get_calculation_source_name())Running results
The module objects of each calculation component can be obtained by importing the package, which can effectively
reduce the package guide code.计算层数：1
计算结果：23.0
计算来源：prefixExpressionOperation
计算层数：2
计算结果：15.0
计算来源：bracketsCalculation2Calculation ManagerFull class name：mathematical_expression/core/manager/CalculationManagement.pyintroduce：The manager is a component designed to use both singletons and dynamic objects. The existence of the manager enables
each component to be obtained by name. Components with the same name have the same storage address in memory, avoiding
the use of redundant components. At the same time, for components that need to use dynamic members, a new component
can also be obtained by a new name.API Usage Examplefrommathematical_expression.core.calculation.numberimportbracketsCalculation2,functionFormulaCalculationfrommathematical_expression.core.managerimportCalculationManagement# Create two parenthesis expression parsing components and a function expression parsing componentbr1=bracketsCalculation2.get_instance("br1")br2=bracketsCalculation2.get_instance("br2")fu1=functionFormulaCalculation.get_instance("fu1")# Get the components with these three names from the managerm_br1=CalculationManagement.get_calculation_by_name("br1")m_br2=CalculationManagement.get_calculation_by_name("br2")m_fu1=CalculationManagement.get_calculation_by_name("fu1")# Through get_ Instance and the manager extract the components obtained by these two methods. In the case of the same name, the two are one objectprint(br1==m_br1)print(br2==m_br2)print(fu1==m_fu1)print(br1==br2)Running resultsThe last three lines are the comparison of memory data. The instantiated components are the same as the components in
the manager, but the components with different names are different.INFO:root:+============================== Welcome to [mathematical expression] ==============================+
INFO:root:+ 	Start time 2022-11-16 16:29:07.660044
INFO:root:+ 	Calculation component manager initialized successfully
INFO:root:+ 	For more information, see: https://github.com/BeardedManZhao/mathematical-expression-py
INFO:root:+--------------------------------------------------------------------------------------------------+
INFO:root:A computing component is registered PrefixExpressionOperation
INFO:root:A computing component is registered BracketsCalculation2
INFO:root:A computing component is registered br1
INFO:root:A computing component is registered br2
INFO:root:A computing component is registered fu1
True
True
True
FalseOperational rule redefinitionFull class name：mathematical_expression/core/manager/ConstantRegion.pyintroduce：There is a constant pool in the framework that stores data that needs to be reused frequently. This data can be
modified in the python version of the framework. Modifying this data can often add more flexibility, but it is
important to note that the modification here may also cause some strange exceptions, so it is up to you to decide if
you want to use redefinition technology.Next, see an example of using redefinition# This is a sample Python script.frommathematical_expression.core.calculation.numberimportbracketsCalculation2frommathematical_expression.core.calculation.number.bracketsCalculation2importBracketsCalculation2frommathematical_expression.core.container.CalculationNumberResultsimportCalculationNumberResultsfrommathematical_expression.core.managerimportConstantRegion# Redefine the sign of the plus signConstantRegion.PLUS_SIGN='$'# Redefine the sign of the multiplication signConstantRegion.MULTIPLICATION_SIGN='@'# Refresh constant area configurationConstantRegion.re_fresh()# Get a calculation component that evaluates nested parenthesis expressionsbracketsCalculation2:BracketsCalculation2=bracketsCalculation2.get_instance("BracketsCalculation")# Create an expression# s: str = "1 + 2 + 4 * (10 - 3)"# TODO The plus sign and multiplication sign here are redefined and can be replaced by new characterss:str="1 $ 2 $ 4 @ (10 - 3)"# Check the expression for errorsbracketsCalculation2.check(s)# Start calculating resultscalculation:CalculationNumberResults=bracketsCalculation2.calculation(s)# Print result valueprint("计算层数："+str(calculation.get_result_layers())+"\n计算结果："+str(calculation.get_result())+"\n计算来源："+calculation.get_calculation_source_name())Running resultsIt can be seen that the operation here is smooth. In the formula, the symbol is redefined计算层数：2
计算结果：31.0
计算来源：BracketsCalculationCalculation component introduceBracketed expressionFull class name：mathematical_expression/core/calculation/number/prefixExpressionOperation.pyintroduceThis component is designed for a mathematical expression without parentheses, but with operations such as addition,
subtraction, multiplication, division and remainder. This component can realize the function with priority
calculation, in which the prefix expression is used to parse and calculate, and the operand and operator are stored on
the stack together with the calculation priority comparison If the current priority is low, first operate the previous
operand and operator with the current operand to form a new value, and then put it on the stack.API Usage ExampleThe operators supported by this component are： a+b a-b a*b a/b a%b# This is a sample Python script.frommathematical_expression.core.calculation.numberimportprefixExpressionOperationfrommathematical_expression.core.calculation.number.prefixExpressionOperationimportPrefixExpressionOperationfrommathematical_expression.core.container.CalculationNumberResultsimportCalculationNumberResults# Gets the calculation component of a function that evaluates an expression without parenthesesprefixExpressionOperation:PrefixExpressionOperation=prefixExpressionOperation.get_instance("p")# Create an expressions:str="1 + 2 + 4 * 10 - 3"# Check the expression for errorsprefixExpressionOperation.check(s)# Start calculating resultscalculation:CalculationNumberResults=prefixExpressionOperation.calculation(s)# Print result valueprint("计算层数："+str(calculation.get_result_layers())+"\n计算结果："+str(calculation.get_result())+"\n计算来源："+calculation.get_calculation_source_name())Running resultsIn the API call, the Running results of the function are printed. It can be seen that the returned value calculated by
the component is a result set object, in which a lot of information about the calculation results is stored.计算层数：2
计算结果：40.0
计算来源：pNested parenthesis expressionFull class name：core/calculation/number/bracketsCalculation2.pyintroduce：Nested parenthesis expression parsing component, which can parse and calculate the results of mathematical expressions
with multiple parentheses, and parse and calculate the priority of nested parentheses. This component relies on "core.
calculation. number. PrefixExpressionOperation", and uses recursion to parse parentheses in this component, Then
provide the innermost expression to "core. calculation. number. PrefixExpressionOperation" for calculation.API Usage ExampleThe operators supported by this component are： a+b a-b a*b a/b a%b ( )# This is a sample Python script.frommathematical_expression.core.calculation.numberimportbracketsCalculation2frommathematical_expression.core.calculation.number.bracketsCalculation2importBracketsCalculation2frommathematical_expression.core.container.CalculationNumberResultsimportCalculationNumberResults# Get a calculation component that evaluates nested parenthesis expressionsbracketsCalculation2:BracketsCalculation2=bracketsCalculation2.get_instance("BracketsCalculation")# Create an expressions:str="1 + 2 + 4 * (10 - 3)"# Check the expression for errorsbracketsCalculation2.check(s)# Start calculating resultscalculation:CalculationNumberResults=bracketsCalculation2.calculation(s)# Print result valueprint("计算层数："+str(calculation.get_result_layers())+"\n计算结果："+str(calculation.get_result())+"\n计算来源："+calculation.get_calculation_source_name())Running resultsIn the API call, the calculation result of the expression is printed. It can be seen that the return value of the
component calculation is a numerical result object, in which a lot of information about the calculation result is
stored.计算层数：2
计算结果：31.0
计算来源：BracketsCalculationMathematical comparison expressionFull class name：core/calculation/bool/booleanCalculation2.pyintroduceA component that uses the comparison operator to determine whether two parenthesis expressions are mutually valid. The
return value is a Boolean result object. This component can compare the size of two numeric values, or the
relationship between two expressions, depending on the component "core. calculation. bool. BooleanCalculation2"API Usage ExampleThe operators supported by this component are shown in the API# This is a sample Python script.frommathematical_expression.core.calculation.boolimportbooleanCalculation2frommathematical_expression.core.calculation.bool.booleanCalculation2importBooleanCalculation2frommathematical_expression.core.container.CalculationBooleanResultsimportCalculationBooleanResultsdefextracted(boolean_calculation2:BooleanCalculation2,s:str):# Check the expression for errorsboolean_calculation2.check(s)# Start calculating resultscalculation:CalculationBooleanResults=boolean_calculation2.calculation(s)# Print result valueprint(f"计算层数：{calculation.get_result_layers()}"f"\t计算结果：{calculation.get_result()}"f"\t计算来源：{calculation.get_calculation_source_name()}")# Get a component that calculates mathematical comparison expressionsbooleanCalculation2:BooleanCalculation2=booleanCalculation2.get_instance("Bool")# Create 3 expressionss1="1 + 2 + 4 * (10 - 3)"s2="2 + 30 + (2 * 3) - 1"s3="1 + 3 * 10"extracted(booleanCalculation2,s1+" > "+s2)# falseextracted(booleanCalculation2,s1+" < "+s2)# trueextracted(booleanCalculation2,s1+" = "+s3)# trueextracted(booleanCalculation2,s1+" == "+s3)# trueextracted(booleanCalculation2,s1+" != "+s3)# falseextracted(booleanCalculation2,s1+" <> "+s3)# falseextracted(booleanCalculation2,s1+" <= "+s3)# trueextracted(booleanCalculation2,s1+" >= "+s3)# trueextracted(booleanCalculation2,s1+" != "+s2)# trueextracted(booleanCalculation2,s1+" <> "+s2)# trueRunning results计算层数：4	计算结果：False	计算来源：Bool
计算层数：4	计算结果：True	计算来源：Bool
计算层数：3	计算结果：True	计算来源：Bool
计算层数：3	计算结果：True	计算来源：Bool
计算层数：3	计算结果：False	计算来源：Bool
计算层数：3	计算结果：False	计算来源：Bool
计算层数：3	计算结果：True	计算来源：Bool
计算层数：3	计算结果：True	计算来源：Bool
计算层数：4	计算结果：True	计算来源：Bool
计算层数：4	计算结果：True	计算来源：BoolInterval accumulation expressionFull class name：core/calculation/number/cumulativeCalculation.pyintroduceIn mathematical expressions, there is often such a formula. The content of the formula is shown in the followingfigure. You can see the number sequence operations that need to be accumulated.Then, you can use the Full class name above to achieve the purpose you need.API Usage ExampleThe syntax level is almost the same as that of other components. The calculation example of the mathematicalexpression written in the component is shown below. What is shown here is the calculation of an accumulativemathematical formula.# This is a sample Python script.frommathematical_expression.core.calculation.numberimportcumulativeCalculation# Get the calculation component of the accumulation formulacumulativeCalculation=cumulativeCalculation.get_instance("cumulative")# Construct a mathematical expression. Here, "n [1,10,1]" is similar to the accumulation symbol in mathematics. N# will increase continuously in this interval. Every increase will be brought into the formula for calculation# Wherein, the last 1 in [1,10,1] represents the increase step, which can realize the accumulation of different equal# difference values in the intervals="n[1,10,1] 2 * (n + 1)"# Check mathematical expressionscumulativeCalculation.check(s)# Calculation resultscalculation=cumulativeCalculation.calculation(s)# Print result valueprint(f"计算层数：{calculation.get_result_layers()}"f"\t计算结果：{calculation.get_result()}"f"\t计算来源：{calculation.get_calculation_source_name()}")Running results计算层数：21	计算结果：130.0	计算来源：cumulativeFunction operation expressionFull class name:core/calculation/number/functionFormulaCalculation.pyintroduceThe framework also supports the operation of some functions. You can use the above classes to write mathematical
expressions that require functions. It should be noted that all functions used in expressions need to be logically
registered in "Calculation Management" so that functions can be accessed during calculationAPI Usage Example# This is a sample Python script.frommathematical_expression.core.calculation.function.FunctionimportFunctionfrommathematical_expression.core.calculation.numberimportfunctionFormulaCalculationfrommathematical_expression.core.managerimportCalculationManagement# 实现一个函数classFunction1(Function):defrun(self,*floats:float):returnfloats[0]*2# Register the implemented function to the managerCalculationManagement.register_function(Function1("DoubleValue"))# Get the function calculation componentfunctionFormulaCalculation=functionFormulaCalculation.get_instance("zhao")# Build an expressions="2 * DoubleValue(2 + 3) + 1"# Check expression formatfunctionFormulaCalculation.check(s)# Start evaluating expressionresult=functionFormulaCalculation.calculation(s)print(f"计算层数：{result.get_result_layers()}"f"\t计算结果：{result.get_result()}"f"\t计算来源：{result.get_calculation_source_name()}")Running resultsINFO:root:Find and prepare the startup function: DoubleValue
计算层数：1	计算结果：21.0	计算来源：BracketsCalculation2Multi parameter function operation expressionFull class name: mathematical_expression/core/calculation/number/functionFormulaCalculation2.pyintroduceFor some expression calculations that use functions in expressions, the above class can be used for operations. It is
an upgraded version of the "core. calculation. number. FunctionFormulaCalculation" class, which has appeared since
version 1.1, is also an extended implementation of its subclass.Compared with the parent class, this component makes up for the deficiency that the parent class can only parse the
function expression with one parameter. In this component, you can use many real parameters for function operations,
such as sum (1,2,3)This type of function is a multiparameter function. Next, let's look at the API usage example, in which the
calculation and results of the multiparameter function expression are shown.frommathematical_expression.core.calculation.function.FunctionimportFunctionfrommathematical_expression.core.calculation.numberimportfunctionFormulaCalculation2frommathematical_expression.core.managerimportCalculationManagement# Implement a functionclassSum(Function):defrun(self,floats:list):res=0fordinfloats:res+=dreturnres# Start to create the function and register it with the managerCalculationManagement.register_function(Sum("sum"))# Get the calculation component that can parse the mathematical expression of multi parameter functionfunctionFormulaCalculation2=functionFormulaCalculation2.get_instance("zhao")# Enable shared poolfunctionFormulaCalculation2.startSharedPool=True# Build the mathematical expression to be calculated# TODO More than one function parameter is used in the following mathematical expressions="2 * (200 - sum(1 + 10.1, 2, 3)) + sum(10, 20)"# Check the mathematical expression for errorsfunctionFormulaCalculation2.check(s)# Calculate the expression and get the resultresult=functionFormulaCalculation2.calculation(s)print(f"计算层数：{result.get_result_layers()}"f"\t计算结果：{result.get_result()}"f"\t计算来源：{result.get_calculation_source_name()}")Running results计算层数：2	计算结果：397.8	计算来源：BracketsCalculation2Fast interval sum calculation component (based on parenthesis expression)Full class name：mathematical_expression/core/calculation/number/fastSumOfIntervalsBrackets.pyintroduceThe new product of version 1.15, the interval fast sum component, is a fast component that sums all elements of an
interval with an equal difference of n. It logically simulates an interval into a mathematical sequence and quickly
sums it through the sum formula.This component implements the shared pool computing function. It will check, calculate, and record the results of the
last time, which can speed up computing. The specific API calls are shown below.frommathematical_expression.core.calculation.numberimportfastSumOfIntervalsBrackets# Get the quick sum calculation component of the intervalfastSumOfIntervalsBrackets=fastSumOfIntervalsBrackets.get_instance("fastSumOfIntervalsBrackets")# Build the interval expression we need to calculate.# The expression is composed of the left and right boundaries of the interval.# The double formulas are separated by commass="1 + 10, 20 - (5 + 2)"# Check the expression. The shared pool has been enabled by default since version 1.2! No need to set manually# fastSumOfIntervalsBrackets.set_start_shared_pool(True)fastSumOfIntervalsBrackets.check(s)# The step size of each element in the interval can be set after version 1.15fastSumOfIntervalsBrackets.step=2# Calculation result valuecalculation=fastSumOfIntervalsBrackets.calculation(s)# Print result valueprint("计算层数："+str(calculation.get_result_layers())+"\n计算结果："+str(calculation.get_result())+"\n计算来源："+calculation.get_calculation_source_name())Running resultsFrom the above code, we can see that the formula for quick interval summation is composed of two parenthesis
expressions separated by commas计算层数：3
计算结果：36.0
计算来源：fastSumOfIntervalsBracketsFast interval cumulative calculation component (based on parenthesis expression)Full class name: mathematical_expression/core/calculation/number/fastSumOfIntervalsBrackets.pyIntroductionA new product of version 1.1.5, the interval fast accumulation component, is a fast component that accumulates all
elements of an interval with an equal difference of n. It logically simulates an interval into a mathematical sequence
and performs fast accumulation through the sum formula.This component implements the shared pool computing function. It will check, calculate, and record the results of the
last time, which can speed up computing. The specific API calls are shown below.frommathematical_expression.core.calculation.numberimportfastMultiplyOfIntervalsBrackets# Get interval fast cumulative calculation componentfastMultiplyOfIntervalsBrackets=fastMultiplyOfIntervalsBrackets.get_instance("fastMultiplyOfIntervalsBrackets")# Build the interval expression we need to calculate. The expression is composed of the left and right boundaries of the interval. The double formulas are separated by commass="1 + 10, 20 - (5 + 2)"# Check the expression. The shared pool has been enabled by default since version 1.15! No need to set manually# fastSumOfIntervalsBrackets.set_start_shared_pool(True)fastMultiplyOfIntervalsBrackets.check(s)# The step size of each element in the interval can be set after version 1.15fastMultiplyOfIntervalsBrackets.step=2# Calculation result valuecalculation=fastMultiplyOfIntervalsBrackets.calculation(s)# Print result valueprint("计算层数："+str(calculation.get_result_layers())+"\n计算结果："+str(calculation.get_result())+"\n计算来源："+calculation.get_calculation_source_name())Running resultsFrom the above code, we can see that the formula for quick interval summation is composed of two parenthesis
expressions separated by commas计算层数：3
计算结果：143.0
计算来源：fastMultiplyOfIntervalsBracketsMore informationdate: 2022-11-14切换至中文文档mathematical-expression-Java