-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluation_of_postfix_expression.py
63 lines (47 loc) · 1.78 KB
/
evaluation_of_postfix_expression.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
"""
Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the basic arithmetic operators like *, /, + and -.
Example 1:
Input: S = "231*+9-"
Output: -4
Explanation:
After solving the given expression,
we have -4 as result.
Example 2:
Input: S = "123+*8-"
Output: -3
Explanation:
After solving the given postfix
expression, we have -3 as result.
Your Task:
You do not need to read input or print anything. Complete the function evaluatePostfixExpression() that takes the string S denoting the expression as input parameter and returns the evaluated value.
Expected Time Complexity: O(|S|)
Expected Auixilliary Space: O(|S|)
Constraints:
1 ≤ |S| ≤ 105
0 ≤ |Si|≤ 9 (And given operators)
"""
class Solution:
#Function to evaluate a postfix expression.
def evaluatePostfix(self, S):
#code here
stack = []
# Iterate through the expression
for char in S:
# If the character is an operand, push it to the stack
if char.isdigit():
stack.append(int(char))
# If the character is an operator, pop two operands from the stack,
# perform the operation, and push the result back to the stack
else:
val2 = stack.pop()
val1 = stack.pop()
if char == '+':
stack.append(val1 + val2)
elif char == '-':
stack.append(val1 - val2)
elif char == '*':
stack.append(val1 * val2)
elif char == '/':
stack.append(val1 // val2) # Integer division
# The final result will be the only element left in the stack
return stack.pop()