Skip to content

Commit f10a5cb

Browse files
prefix_evaluation: Add alternative recursive implementation (#12646)
* prefix_evaluation: Add alternative recursive implementation * improve doc * better variable name calc->operators * Update prefix_evaluation.py * Update prefix_evaluation.py * Update prefix_evaluation.py * Update prefix_evaluation.py --------- Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent 74b540a commit f10a5cb

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

data_structures/stacks/prefix_evaluation.py

+36-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
"""
2-
Python3 program to evaluate a prefix expression.
2+
Program to evaluate a prefix expression.
3+
https://en.wikipedia.org/wiki/Polish_notation
34
"""
45

5-
calc = {
6+
operators = {
67
"+": lambda x, y: x + y,
78
"-": lambda x, y: x - y,
89
"*": lambda x, y: x * y,
@@ -31,6 +32,10 @@ def evaluate(expression):
3132
21
3233
>>> evaluate("/ * 10 2 + 4 1 ")
3334
4.0
35+
>>> evaluate("2")
36+
2
37+
>>> evaluate("+ * 2 3 / 8 4")
38+
8.0
3439
"""
3540
stack = []
3641

@@ -45,11 +50,39 @@ def evaluate(expression):
4550
# push the result onto the stack again
4651
o1 = stack.pop()
4752
o2 = stack.pop()
48-
stack.append(calc[c](o1, o2))
53+
stack.append(operators[c](o1, o2))
4954

5055
return stack.pop()
5156

5257

58+
def evaluate_recursive(expression: list[str]):
59+
"""
60+
Alternative recursive implementation
61+
62+
>>> evaluate_recursive(['2'])
63+
2
64+
>>> expression = ['+', '*', '2', '3', '/', '8', '4']
65+
>>> evaluate_recursive(expression)
66+
8.0
67+
>>> expression
68+
[]
69+
>>> evaluate_recursive(['+', '9', '*', '2', '6'])
70+
21
71+
>>> evaluate_recursive(['/', '*', '10', '2', '+', '4', '1'])
72+
4.0
73+
"""
74+
75+
op = expression.pop(0)
76+
if is_operand(op):
77+
return int(op)
78+
79+
operation = operators[op]
80+
81+
a = evaluate_recursive(expression)
82+
b = evaluate_recursive(expression)
83+
return operation(a, b)
84+
85+
5386
# Driver code
5487
if __name__ == "__main__":
5588
test_expression = "+ 9 * 2 6"

0 commit comments

Comments
 (0)