1+ '''
2+ Postfix Evaluate
3+
4+ When arithmetic expressions are given in the familiar infix notation 2 + 3 * 4, we need to use
5+ parentheses to force a different evaluation order than the usual PEMDAS order determined by
6+ precedence and associativity . Writing arithmetic expressions in postfix notation (also known as
7+ Reverse Polish Notation ) may look strange to us humans accustomed to the conventional infix
8+ notation, but is computationally much easier to handle, since postfix notation allows any evaluation
9+ order to be expressed without using any parentheses at all! A postfix expression is given as a list of
10+ items that can be either individual integers or one of the strings '+' , '-' , '*' and '/' for the four
11+ possible arithmetic operators. Calculate the result of the postfix expression.
12+
13+ Input: [2, 3, '+', 4, '*']
14+ Output: 20
15+ Output explanation: (2+3) * 4
16+
17+ Input: [1, 2, 3, 4, 5, 6, '*', '*', '*', '*', '*']
18+ Output: 720
19+ Output explanation: 1 * 2 * 3 * 4 * 5 * 6
20+
21+ =========================================
22+ Use stack, save all numbers into the stack.
23+ When a sign comes, pop the last 2 numbers from the stack, calculate their result and return the result into the stack.
24+ Time Complexity: O(N)
25+ Space Complexity: O(N)
26+ '''
27+
28+
29+ ############
30+ # Solution #
31+ ############
32+
33+ from collections import deque
34+
35+ def postfix_evaluate (items ):
36+ stack = deque ()
37+ # lambda functions for all 4 operations
38+ operations = {
39+ '+' : (lambda a , b : a + b ),
40+ '-' : (lambda a , b : a - b ),
41+ '*' : (lambda a , b : a * b ),
42+ '/' : (lambda a , b : 0 if (b == 0 ) else (a // b ))
43+ }
44+
45+ for item in items :
46+ # check if the item is a sign or a number
47+ if item in operations :
48+ b = stack .pop ()
49+ a = stack .pop ()
50+
51+ result = operations [item ](a , b )
52+
53+ stack .append (result )
54+ else :
55+ stack .append (item )
56+
57+ return stack .pop ()
58+
59+
60+ ###########
61+ # Testing #
62+ ###########
63+
64+ # Test 1
65+ # Correct result => 20
66+ print (postfix_evaluate ([2 , 3 , '+' , 4 , '*' ]))
67+
68+ # Test 2
69+ # Correct result => 14
70+ print (postfix_evaluate ([2 , 3 , 4 , '*' , '+' ]))
71+
72+ # Test 3
73+ # Correct result => 0
74+ print (postfix_evaluate ([3 , 3 , 3 , '-' , '/' ]))
75+
76+ # Test 4
77+ # Correct result => 2
78+ print (postfix_evaluate ([7 , 3 , '/' ]))
79+
80+ # Test 5
81+ # Correct result => 720
82+ print (postfix_evaluate ([1 , 2 , 3 , 4 , 5 , 6 , '*' , '*' , '*' , '*' , '*' ]))
0 commit comments