Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
Example
Input: [“4”, “13”, “5”, “/”, “+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Solution
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
def divi(ia, ib):
ia = int(ia)
ib = int(ib)
return ia // ib if ia ^ ib >= 0 else -(ia//-ib)
operators = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':divi}
stack = []
for t in tokens:
if t in operators:
a = stack.pop()
b = stack.pop()
stack.append(operators[t](b, a))
else:
stack.append(int(t))
return stack[0]