data_structures.stacks.postfix_evaluation¶
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
- 9 | push(9) | 5,6,9
pop(9) | 5,6pop(6) | 5
push(6*9) | 5,54pop(54) | 5pop(5) |
push(5+54) | 59Result = 59
Attributes¶
Functions¶
|
Evaluate postfix expression using a stack. |
|
Converts the given data to the appropriate number if it is indeed a number, else |
Module Contents¶
- data_structures.stacks.postfix_evaluation.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
- data_structures.stacks.postfix_evaluation.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
- data_structures.stacks.postfix_evaluation.OPERATORS¶
- data_structures.stacks.postfix_evaluation.UNARY_OP_SYMBOLS = ('-', '+')¶
- data_structures.stacks.postfix_evaluation.expression¶