150. 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.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Solution: Stack
OP = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: int(float(a) / b)
}
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for token in tokens:
try:
num = int(token)
stack.append(num)
except ValueError:
if token not in OP:
raise Exception("invalid operator")
if len(stack) < 2:
raise Exception("invalid numbers")
b = stack.pop()
a = stack.pop()
num = OP[token](a, b)
stack.append(num)
if len(stack) != 1:
raise Exception("invalid numbers")
return stack.pop()
Lessons:
- Python evaluates
-1 / 2into-1instead of0, so we useint(float(a) / b)for division.