Python solution with comments (don't use eval() function).


  • 20
    C
    def evalRPN(self, tokens):
        stack = []
        for t in tokens:
            if t not in ["+", "-", "*", "/"]:
                stack.append(int(t))
            else:
                r, l = stack.pop(), stack.pop()
                if t == "+":
                    stack.append(l+r)
                elif t == "-":
                    stack.append(l-r)
                elif t == "*":
                    stack.append(l*r)
                else:
                    # here take care of the case like "1/-22",
                    # in Python 2.x, it returns -1, while in 
                    # Leetcode it should return 0
                    if l*r < 0 and l % r != 0:
                        stack.append(l/r+1)
                    else:
                        stack.append(l/r)
        return stack.pop()

  • 0
    T

    same idea

    def evalRPN(self, tokens):  
            def divi(ia, ib):
                return ia / ib if ia ^ ib >= 0 else -(ia/-ib)
            operatorDict = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':divi}
            sta = []
            for token in tokens:
                if token in operatorDict:
                    secondEle = sta.pop()
                    sta.append(operatorDict[token](sta.pop(), secondEle))
                else:
                    sta.append(int(token))
            return sta[0]

  • 2

    @caikehe You can use int(float(l) / r) for division instead of` if statement. int()will take the part of integer, which is wanted by this question.


  • 0
    A

    Thank you for the great answers.
    While you can still use eval but take '/' as another if condition:

    
            stack = []
            for t in tokens:
                
                if t in ('+','-','*','/'):
                    v1 = stack.pop()
                    v2 = stack.pop()
                
                    if t=='/': 
                        v = int(float(v2)/float(v1))
                    else:
                        v = eval(v2+t+v1)
                        
                    stack.append(str(v))
                
                else:
                    stack.append(t)
    
            return int(stack[0])
    

Log in to reply
 

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