zoukankan      html  css  js  c++  java
  • 169-150. 逆波兰表达式求值

    
    这个是逆波兰表达式(其中python3执行,否则会出现计算错误)
    class Solution(object):
    
        def evalRPN(self, tokens):
            """
            :type tokens: List[str]
            :rtype: int
            """
            operation_list = ("+", "-", "*", "/")
            stack = []
            length = len(tokens)
            if length < 1:
                return None
            for i in range(length):
                if tokens[i] not in operation_list:
                    stack.append(tokens[i])
                else:
                    if not stack:
                        return None
                    num1 = stack.pop()
                    if not stack:
                        return None
                    num2 = stack.pop()
    
                    if tokens[i] == "+":
                        result = int(num2) + int(num1)
                    elif tokens[i] == "-":
                        result = int(num2) - int(num1)
                    elif tokens[i] == "/":
                        result = int(num2) / int(num1)
                    else:
                        result = int(num2) * int(num1)
                    stack.append(result)
            return stack[-1]
    
    
    if __name__ == '__main__':
        temperatures = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
        s1 = Solution()
        root = s1.evalRPN(temperatures)
        print(root
    
  • 相关阅读:
    mongodb数据库shell
    PLINK pca
    xgboost 安装
    tensorflow之损失函数
    php,mysql存储过程的简单例子
    ECharts初体验
    mysql常用连接查询
    php流程控制
    php循环
    高效率php注意事项
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14392105.html
Copyright © 2011-2022 走看看