-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluateRPN.py
More file actions
35 lines (32 loc) · 915 Bytes
/
EvaluateRPN.py
File metadata and controls
35 lines (32 loc) · 915 Bytes
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
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
l = []
while len(tokens) > 0:
temp = tokens.pop(0)
if not self.isOperator(temp):
l.append(int(temp))
else:
opt = temp
y = l.pop()
x = l.pop()
l.append(self.operation(x,y,opt))
return l[0]
def operation(self,x,y,opt):
if opt == '+':
return x+y
elif opt == '-':
return x-y
elif opt == '*':
return x*y
elif opt == '/':
# note that the division in Python is floor
if x*y < 0:
return - (-x/y)
return x/y
def isOperator(self,opt):
if opt in '+-*/':
return True
else:
return False