mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

【问题】

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

【代码】

class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        stack = []
        for item in tokens:
            if item not in ("+", "-", "*", "/"):
                stack.append(int(item))
            else:
                op2 = stack.pop()
                op1 = stack.pop()
                if item == "+":
                    stack.append(op1 + op2)
                elif item == "-":
                    stack.append(op1 - op2)
                elif item == "*":
                    stack.append(op1 * op2)
                elif item == "/":
                    stack.append(int(op1 *1.0 / op2))
        return stack[0]


posted on 2017-07-22 15:14  mthoutai  阅读(192)  评论(0编辑  收藏  举报