zoukankan      html  css  js  c++  java
  • [leetcode]Evaluate Reverse Polish Notation @ Python

    原题地址:https://oj.leetcode.com/problems/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

    解题思路:这道题是经典的逆波兰式求值。具体思路是:开辟一个空栈,遇到数字压栈,遇到运算符弹出栈中的两个数进行运算,并将运算结果压栈,最后栈中只剩下一个数时,就是所求结果。这里需要注意的一点是python中的'/'除法和c语言不太一样。在python中,(-1)/2=-1,而在c语言中,(-1)/2=0。也就是c语言中,除法是向零取整,即舍弃小数点后的数。而在python中,是向下取整的。而这道题的oj是默认的c语言中的语法,所以需要在遇到'/'的时候注意一下。

    代码:

    class Solution:
        # @param tokens, a list of string
        # @return an integer
        def evalRPN(self, tokens):
            stack = []
            for i in range(0,len(tokens)):
                if tokens[i] != '+' and tokens[i] != '-' and tokens[i] != '*' and tokens[i] != '/':
                    stack.append(int(tokens[i]))
                else:
                    a = stack.pop()
                    b = stack.pop()
                    if tokens[i] == '+':
                        stack.append(a+b)
                    if tokens[i] == '-':
                        stack.append(b-a)
                    if tokens[i] == '*':
                        stack.append(a*b)
                    if tokens[i] == '/':
                        if a*b < 0:
                            stack.append(-((-b)/a))
                        else:
                            stack.append(b/a)
            return stack.pop()
  • 相关阅读:
    Java单例多例的线程安全问题(转)
    Class.forName( )、class.getClassLoader().getResourceAsStream、newInstance()
    new 和Class.forName()有什么区别?(转)
    PS
    Fine BI
    Ipython
    微软推 Azure 机器学习工具:Algorithm Cheat Sheet
    MySQL基本数据类型
    Httprunner3.X+jenkins持续集成
    MSF使用之信息收集
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3760530.html
Copyright © 2011-2022 走看看