# # 【LeetCode】150. Evaluate Reverse Polish Notation 解题报告（Python）

## # 题目描述：

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
``````

## # 解题方法

python 有个牛逼的函数，就是`eval()`，可以给它一个运算表达式，直接给你求值。中缀表达式转正常表达式很简单了，直接用栈就行。

``````class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
operators = ['+', '-', '*', '/']
for token in tokens:
if token not in operators:
stack.append(token)
else:
b = stack.pop()
a = stack.pop()
if token == '/' and int(a) * int(b) < 0:
res = eval('-' + '(' + '-' + a + '/' + b + ')')
else:
res = eval(a + token + b)
stack.append(str(res))
return int(stack.pop())
``````

``````class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
operators = ['+', '-', '*', '/']
for token in tokens:
if token not in operators:
stack.append(token)
else:
b = stack.pop()
a = stack.pop()
if token == '/':
res = int(operator.truediv(int(a), int(b)))
else:
res = eval(a + token + b)
stack.append(str(res))
return int(stack.pop())
``````

2018 年 3 月 14 日