## [Leetcode]Evaluate Reverse Polish Notation 作者是 在线疯狂 发布于 2014年10月16日 在 LeetCode, 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的负数除法运算与Java存在差异，而Leetcode此题的标准答案以Java程序的运算结果为准。

### Python代码如下：

``````class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
operators = ["+", "-", "*", "/"]
operand_list = []
for token in tokens:
if token in operators:
y, x = operand_list.pop(), operand_list.pop()
operand_list.append(self.getVal(x, y, token))
else:
operand_list.append(int(token))
return operand_list[0]

def getVal(self, x, y, operator):
return {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: int(float(x) / y),
}[operator](x, y)
``````

Pingbacks已关闭。