LeetCode-Evaluate Reverse Polish Notation (Python)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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

【代码】

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]





以上是关于LeetCode-Evaluate Reverse Polish Notation (Python)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Evaluate Division

REVERSE!REVERSE!REVERSE!

c++ 中reverse函数用法

inverse reverse converse有何区别

Django中reverse()和reverse_lazy()的区别

攻防世界 reverse 进阶 10 Reverse Box