计算逆波兰式(后缀表达式)的值

计算逆波兰式(后缀表达式)的值

运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式

例如:

  ["20", "10", "+", "30", "*"] -> ((20 + 10) * 30) -> 900
  ["40", "130", "50", "/", "+"] -> (40 + (130 / 50)) -> 42

 

代码实现:

class Solution:
    def evalRPN(self , tokens ):
        # write code here
        return self.fun(tokens)
    def fun(self,tokens):
        flag = ['+','-','*','/']
        list = []
        for i in range(len(tokens)):
            if tokens[i] in flag:
                len_list = len(list)
                result = self.claculate(list[len_list - 2],list[len_list - 1],tokens[i])
                del list[len_list - 1]
                del list[len_list - 2]
                list.append(str(result))
            else:
                list.append(tokens[i])
        return int(list[0])
    def claculate(self,num1,num2,sign):
        if sign == "+":
            return int(num1) + int(num2)
        elif sign == "-":
            return int(num1) - int(num2)
        elif sign == "*":
            return int(num1) * int(num2)
        elif sign == "/":
            return int(int(num1) / int(num2))

你可能感兴趣的:(算法,算法,逆波兰式)