Skip to content

Commit c4f248d

Browse files
committed
prefix_evaluation: Add alternative recursive implementation
1 parent fff34ed commit c4f248d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

data_structures/stacks/prefix_evaluation.py

+24
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,30 @@ def evaluate(expression):
5050
return stack.pop()
5151

5252

53+
def evaluate_recursive(expression: list):
54+
"""
55+
Alternative implementation
56+
57+
>>> evaluate_recursive(['2'])
58+
2.0
59+
>>> expression = ['+', '*', '2', '3', '/', '8', 4]
60+
>>> evaluate_recursive(expression)
61+
8.0
62+
>>> expression
63+
[]
64+
"""
65+
66+
op = expression.pop(0)
67+
if op not in calc:
68+
return float(op)
69+
70+
operation = calc[op]
71+
72+
a = evaluate_recursive(expression)
73+
b = evaluate_recursive(expression)
74+
return operation(a, b)
75+
76+
5377
# Driver code
5478
if __name__ == "__main__":
5579
test_expression = "+ 9 * 2 6"

0 commit comments

Comments
 (0)