Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack = []
lens = len(tokens)
if lens == 0:
return stack
for i in xrange(lens):
if tokens[i] == '+' or tokens[i] == '-' or tokens[i] == '*' or tokens[i] == '/':
b = int(stack[-1])
del stack[-1]
a = int(stack[-1])
del stack[-1]
if tokens[i] == '+':
stack.append(str(a+b))
elif tokens[i] == '-':
stack.append(str(a-b))
elif tokens[i] == '*':
stack.append(str(a*b))
elif tokens[i] == '/':
stack.append(str(a/b if a*b>0 else -((-a)/b)))
else:
stack.append(tokens[i])
return int(stack[0])