package_name_to_import_with.simplify module#

Evaluate simplification expressions.

class Parentheses(value)[source]#

Bases: str, enum.Enum

Define supported brackets.

LEFT = '('#
RIGHT = ')'#
clean_and_tokenise_expression(raw_expression)[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)[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

  1. Initiate operator stack and output queue.

  2. Modify based on token type.

    • Number

      1. Convert to number (using float).

      2. Add to output_queue.

    • Operator

      1. Convert to operator (using BinaryArithmeticOperator).

      2. Move top lower precedence operators from operator_stack into output_queue.

      3. Add to operator_stack.

    • Left Parenthesis

      1. Convert to bracket (using Parentheses).

    • Right Parenthesis

      1. Convert to bracket (using Parentheses).

      2. Move operators from operator_stack into output_queue till left bracket.

      3. Discard left bracket from top of operator_stack.

References

Wikipedia.

evaluate_postfix_expression(postfix_expression)[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:

float

solve_simplification(expression)[source]#

Evaluate arithmetic expression.

Parameters:

expression (str) -- standard arithmetic expression

Returns:

result of arithmetic expression

Return type:

float

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