My python consice solution


  • 2
    class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        stack  = [] 
        for i in tokens:
            try:
                temp = int(i)
                stack.append(temp)
            except Exception, e:         
                b,a=stack[-1],stack[-2]
                stack.pop()
                stack.pop()
                if i == '+':    a = a+b
                elif i=='-':    a = a-b
                elif i=='*':    a = a*b
                elif i=='/':    a = int(a*1.0/b)
                stack.append(a)
               
        return stack[-1]

  • 1
    R

    No, this is not concise. You shouldn't even rely on exception to replace normal if...else, because raising and capturing an exception is much slower.

    By the way, there is a real concise solution in python contains only 6 lines of code inside the evalRPN(). Wanna take another try?


  • 0

    What's your 6-liner?


  • 0
    C

    b,a=stack[-1],stack[-2]
    stack.pop()
    stack.pop()
    in Python can be shorten as b, a = stack.pop(), stack.pop().


Log in to reply
 

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