Evaluate Reverse Polish Notation
Description:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Example
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
Code:
class Solution:
"""
@param tokens: The Reverse Polish Notation
@return: the value
"""
def evalRPN(self, tokens):
# write your code here
stack = []
for i in tokens:
if i.isnumeric() or i[1:].isnumeric():
stack.append(int(i))
else:
par2 = stack.pop()
par1 = stack.pop()
if i=='+':
stack.append(par1+par2)
if i=='-':
stack.append(par1-par2)
if i=='*':
stack.append(par1*par2)
if i=='/':
stack.append(int(par1/par2))
return int(stack.pop())