lintcode练习-424. 逆波兰表达式求值

描述

求逆波兰表达式的值。

在逆波兰表达法中,其有效的运算符号包括 +-*/ 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

您在真实的面试中是否遇到过这个题?  是

说明

什么是逆波兰表达式?

样例

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

实现代码:

class Solution:
    """
    @param tokens: The Reverse Polish Notation
    @return: the value
    """
    def evalRPN(self, tokens):
        # write your code here
        stack = []
        operator = ['+', '-', '*', '/']
        for item in tokens:
            if item in operator:
                num2 = stack.pop()
                num1 = stack.pop()
                stack.append(self.operation(int(num1), int(num2), item))
            else:    
        
                stack.append(item)
        
        return int(stack.pop())
    
    
    
    def operation(self, num1, num2, operator):
        if operator == '+':
            return num1 + num2
        elif operator == '-':
            return num1 - num2
        elif operator == '*':
            return num1 * num2
        elif operator == '/':
            return num1 / num2
 

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81387431