-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvaluateExpression.py
38 lines (35 loc) · 1012 Bytes
/
EvaluateExpression.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
# https://www.interviewbit.com/problems/evaluate-expression/
def isOperator(s):
return s == "+" or s == "-" or s == "*" or s == "/"
def applyOperator(a, b, o):
a = int(a)
b = int(b)
if o == "+":
return a + b
elif o == "-":
return a - b
elif o == "*":
return a * b
elif o == "/":
return a // b
class Solution:
# @param A : list of strings
# @return an integer
def evalRPN(self, A):
nums = []
operators = []
for elem in A:
if isOperator(elem):
if len(nums) > 1:
b = nums.pop()
a = nums.pop()
nums.append(applyOperator(a, b, elem))
else:
operators.apped(elem)
else:
nums.append(elem)
while operators:
b = nums.pop()
a = nums.pop()
nums.append(applyOperator(a, b, operators.pop()))
return nums[0]