Skip to content

Commit ab54d92

Browse files
akashgkrishnancclauss
authored andcommitted
Adding in the evaluate postfix notation using Stack (TheAlgorithms#2598)
* Create evaluate_postfix_notations.py Adding in the evaluate postfix notation using Stacks one of the common use with simple stack question creating a new file for the data structure of stacks * Create evaluate_postfix_notations.py Adding in the evaluate postfix notation using Stacks one of the common use with simple stack question creating a new file for the data structure of stacks * Delete evaluate_postfix_notations.py * Evaluate postfix expression stack clean approach Sending in the PR again as the Previous request failed in pre commit * Update evaluate_postfix_notations.py * Update evaluate_postfix_notations.py Made changes as per the required for fixing the failing pre-commits. * Update evaluate_postfix_notations.py Made changes as suggested by @cclauss * Update evaluate_postfix_notations.py fixed pre-commit fails * Update evaluate_postfix_notations.py fixing pre-commit fails * Update evaluate_postfix_notations.py Deleted trailing white spaces causing pre-commits to fail * Update data_structures/stacks/evaluate_postfix_notations.py Co-authored-by: Christian Clauss <[email protected]> * Update data_structures/stacks/evaluate_postfix_notations.py Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent 5c86853 commit ab54d92

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
The Reverse Polish Nation also known as Polish postfix notation
3+
or simply postfix notation.
4+
https://en.wikipedia.org/wiki/Reverse_Polish_notation
5+
Classic examples of simple stack implementations
6+
Valid operators are +, -, *, /.
7+
Each operand may be an integer or another expression.
8+
"""
9+
10+
11+
def evaluate_postfix(postfix_notation: list) -> int:
12+
"""
13+
>>> evaluate_postfix(["2", "1", "+", "3", "*"])
14+
9
15+
>>> evaluate_postfix(["4", "13", "5", "/", "+"])
16+
6
17+
>>> evaluate_postfix([])
18+
0
19+
"""
20+
if not postfix_notation:
21+
return 0
22+
23+
operations = {"+", "-", "*", "/"}
24+
stack = []
25+
26+
for token in postfix_notation:
27+
if token in operations:
28+
b, a = stack.pop(), stack.pop()
29+
if token == "+":
30+
stack.append(a + b)
31+
elif token == "-":
32+
stack.append(a - b)
33+
elif token == "*":
34+
stack.append(a * b)
35+
else:
36+
if a * b < 0 and a % b != 0:
37+
stack.append(a // b + 1)
38+
else:
39+
stack.append(a // b)
40+
else:
41+
stack.append(int(token))
42+
43+
return stack.pop()
44+
45+
46+
if __name__ == "__main__":
47+
import doctest
48+
49+
doctest.testmod()

0 commit comments

Comments
 (0)