data_structures.stacks.postfix_evaluation ========================================= .. py:module:: data_structures.stacks.postfix_evaluation .. autoapi-nested-parse:: Reverse Polish Nation is also known as Polish postfix notation or simply postfix notation. https://en.wikipedia.org/wiki/Reverse_Polish_notation Classic examples of simple stack implementations. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Output: Enter a Postfix Equation (space separated) = 5 6 9 * + Symbol | Action | Stack ----------------------------------- 5 | push(5) | 5 6 | push(6) | 5,6 9 | push(9) | 5,6,9 | pop(9) | 5,6 | pop(6) | 5 * | push(6*9) | 5,54 | pop(54) | 5 | pop(5) | + | push(5+54) | 59 Result = 59 Attributes ---------- .. autoapisummary:: data_structures.stacks.postfix_evaluation.OPERATORS data_structures.stacks.postfix_evaluation.UNARY_OP_SYMBOLS data_structures.stacks.postfix_evaluation.expression Functions --------- .. autoapisummary:: data_structures.stacks.postfix_evaluation.evaluate data_structures.stacks.postfix_evaluation.parse_token Module Contents --------------- .. py:function:: evaluate(post_fix: list[str], verbose: bool = False) -> float Evaluate postfix expression using a stack. >>> evaluate(["0"]) 0.0 >>> evaluate(["-0"]) -0.0 >>> evaluate(["1"]) 1.0 >>> evaluate(["-1"]) -1.0 >>> evaluate(["-1.1"]) -1.1 >>> evaluate(["2", "1", "+", "3", "*"]) 9.0 >>> evaluate(["2", "1.9", "+", "3", "*"]) 11.7 >>> evaluate(["2", "-1.9", "+", "3", "*"]) 0.30000000000000027 >>> evaluate(["4", "13", "5", "/", "+"]) 6.6 >>> evaluate(["2", "-", "3", "+"]) 1.0 >>> evaluate(["-4", "5", "*", "6", "-"]) -26.0 >>> evaluate([]) 0 >>> evaluate(["4", "-", "6", "7", "/", "9", "8"]) Traceback (most recent call last): ... ArithmeticError: Input is not a valid postfix expression Parameters ---------- post_fix: The postfix expression is tokenized into operators and operands and stored as a Python list verbose: Display stack contents while evaluating the expression if verbose is True Returns ------- float The evaluated value .. py:function:: parse_token(token: str | float) -> float | str Converts the given data to the appropriate number if it is indeed a number, else returns the data as it is with a False flag. This function also serves as a check of whether the input is a number or not. Parameters ---------- token: The data that needs to be converted to the appropriate operator or number. Returns ------- float or str Returns a float if `token` is a number or a str if `token` is an operator .. py:data:: OPERATORS .. py:data:: UNARY_OP_SYMBOLS :value: ('-', '+') .. py:data:: expression