Skip to content

Commit 4607cd4

Browse files
M0r13nonlinejudge95
authored andcommitted
Add a program to evaluate a string in prefix notation (Polish Notation) (TheAlgorithms#1675)
* Create infix_evaluation.py * fix doctests * Rename infix_evaluation.py to prefix_evaluation.py * Add prefix_evaluation.py to directory
1 parent 2cb6a65 commit 4607cd4

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
128128
* Trie
129129
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
130+
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/prefix_evaluation.py)
130131

131132
## Digital Image Processing
132133
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Python3 program to evaluate a prefix expression.
3+
"""
4+
5+
calc = {
6+
"+": lambda x, y: x + y,
7+
"-": lambda x, y: x - y,
8+
"*": lambda x, y: x * y,
9+
"/": lambda x, y: x / y,
10+
}
11+
12+
13+
def is_operand(c):
14+
"""
15+
Return True if the given char c is an operand, e.g. it is a number
16+
17+
>>> is_operand("1")
18+
True
19+
>>> is_operand("+")
20+
False
21+
"""
22+
return c.isdigit()
23+
24+
25+
def evaluate(expression):
26+
"""
27+
Evaluate a given expression in prefix notation.
28+
Asserts that the given expression is valid.
29+
30+
>>> evaluate("+ 9 * 2 6")
31+
21
32+
>>> evaluate("/ * 10 2 + 4 1 ")
33+
4.0
34+
"""
35+
stack = []
36+
37+
# iterate over the string in reverse order
38+
for c in expression.split()[::-1]:
39+
40+
# push operand to stack
41+
if is_operand(c):
42+
stack.append(int(c))
43+
44+
else:
45+
# pop values from stack can calculate the result
46+
# push the result onto the stack again
47+
o1 = stack.pop()
48+
o2 = stack.pop()
49+
stack.append(calc[c](o1, o2))
50+
51+
return stack.pop()
52+
53+
54+
# Driver code
55+
if __name__ == "__main__":
56+
test_expression = "+ 9 * 2 6"
57+
print(evaluate(test_expression))
58+
59+
test_expression = "/ * 10 2 + 4 1 "
60+
print(evaluate(test_expression))

0 commit comments

Comments
 (0)