Python recursive solution, no need to append back to stack


  • 0
    A
    def evalRPN(self, tokens):
            """
            :type tokens: List[str]
            :rtype: int
            """
            def cal(op,ls,oper):
                num1 = ls.pop();
                if num1 in oper:
                    num1 = cal(num1,ls,oper);
                num2 = ls.pop();
                if num2 in oper:
                    num2 = cal(num2,ls,oper);
                if op == "+":
                    return int(num2)+int(num1);
                elif op == "-":
                    return int(num2)-int(num1);
                elif op == "*":
                    return int(num2)*int(num1);
                elif op == "/":
                    return int(float(num2)/int(num1));
                
            oper = ["+","-","*","/"];
            o = tokens.pop();
            if o in oper:
                return cal(o,tokens,oper);
            else:
                return int(o);
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.