data_structures.stacks.prefix_evaluation

Program to evaluate a prefix expression. https://en.wikipedia.org/wiki/Polish_notation

Attributes

operators

test_expression

Functions

evaluate(expression)

Evaluate a given expression in prefix notation.

evaluate_recursive(expression)

Alternative recursive implementation

is_operand(c)

Return True if the given char c is an operand, e.g. it is a number

Module Contents

data_structures.stacks.prefix_evaluation.evaluate(expression)

Evaluate a given expression in prefix notation. Asserts that the given expression is valid.

>>> evaluate("+ 9 * 2 6")
21
>>> evaluate("/ * 10 2 + 4 1 ")
4.0
>>> evaluate("2")
2
>>> evaluate("+ * 2 3 / 8 4")
8.0
data_structures.stacks.prefix_evaluation.evaluate_recursive(expression: list[str])

Alternative recursive implementation

>>> evaluate_recursive(['2'])
2
>>> expression = ['+', '*', '2', '3', '/', '8', '4']
>>> evaluate_recursive(expression)
8.0
>>> expression
[]
>>> evaluate_recursive(['+', '9', '*', '2', '6'])
21
>>> evaluate_recursive(['/', '*', '10', '2', '+', '4', '1'])
4.0
data_structures.stacks.prefix_evaluation.is_operand(c)

Return True if the given char c is an operand, e.g. it is a number

>>> is_operand("1")
True
>>> is_operand("+")
False
data_structures.stacks.prefix_evaluation.operators
data_structures.stacks.prefix_evaluation.test_expression = '+ 9 * 2 6'