package_name_to_import_with.simplify module#
Evaluate simplification expressions.
- class Parentheses(value)[source]#
Bases:
CustomStrEnumDefine supported brackets.
- LEFT = '('#
- RIGHT = ')'#
- clean_and_tokenise_expression(raw_expression: str) Iterator[Match[str]][source]#
Extract tokens from arithmetic expression after pre-processing.
- Parameters:
raw_expression (
str) -- infix expression- Returns:
tokens in standard arithmetic expression
- Return type:
collections.abc.Iterator[re.Match[str]]- Raises:
ValueError -- if unsupported characters are passed
- convert_infix_expression(infix_expression_tokens: Iterator[Match[str]]) list[BinaryArithmeticOperator | float][source]#
Convert standard arithmetic expression into reverse Polish notation.
This implements shunting yard algorithm following pseudocode section in Wikipedia.
- Parameters:
infix_expression_tokens (
collections.abc.Iterator[re.Match[str]]) -- tokens in standard arithmetic expression- Returns:
postfix arithmetic expression
- Return type:
list[BinaryArithmeticOperator | float]- Raises:
ValueError -- if brackets are not matching
Notes
Initiate operator stack and output queue.
Modify based on token type.
Number
Convert to number (using float).
Add to
output_queue.
Operator
Convert to operator (using BinaryArithmeticOperator).
Move top lower precedence operators from
operator_stackintooutput_queue.Add to
operator_stack.
Left Parenthesis
Convert to bracket (using Parentheses).
Right Parenthesis
Convert to bracket (using Parentheses).
Move operators from
operator_stackintooutput_queuetill left bracket.Discard left bracket from top of
operator_stack.
References
- evaluate_postfix_expression(postfix_expression: list[BinaryArithmeticOperator | float]) float[source]#
Evaluate postfix arithmetic expression in reverse Polish notation.
- Parameters:
postfix_expression (
list[BinaryArithmeticOperator | float]) -- elements of arithmetic expression in postfix format- Returns:
result of arithmetic expression
- Return type:
- solve_simplification(expression: str) float[source]#
Evaluate arithmetic expression.
- Parameters:
expression (
str) -- standard arithmetic expression- Returns:
result of arithmetic expression
- Return type:
Examples
>>> from package_name_to_import_with import solve_simplification >>> solve_simplification("0 + 1 - 2 * 3 / 4") -0.5 >>> solve_simplification("5 * 6 / (7 + 8) - 9") -7.0