-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathprefix_evaluation.py
92 lines (73 loc) · 1.94 KB
/
prefix_evaluation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Program to evaluate a prefix expression.
https://en.wikipedia.org/wiki/Polish_notation
"""
operators = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
}
def 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
"""
return c.isdigit()
def 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
"""
stack = []
# iterate over the string in reverse order
for c in expression.split()[::-1]:
# push operand to stack
if is_operand(c):
stack.append(int(c))
else:
# pop values from stack can calculate the result
# push the result onto the stack again
o1 = stack.pop()
o2 = stack.pop()
stack.append(operators[c](o1, o2))
return stack.pop()
def 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
"""
op = expression.pop(0)
if is_operand(op):
return int(op)
operation = operators[op]
a = evaluate_recursive(expression)
b = evaluate_recursive(expression)
return operation(a, b)
# Driver code
if __name__ == "__main__":
test_expression = "+ 9 * 2 6"
print(evaluate(test_expression))
test_expression = "/ * 10 2 + 4 1 "
print(evaluate(test_expression))