A simple Python solution - O(n) 72ms


  • 9
    G
    class Solution:
        # @param {string[]} tokens
        # @return {integer}
        def __init__(self):
            self.operators = {
                '+': lambda y, x: x + y,
                '-': lambda y, x: x - y,
                '*': lambda y, x: x * y,
                '/': lambda y, x: int(operator.truediv(x, y))
            }
    
        def evalRPN(self, tokens):
            if not tokens:
                return 0
    
            stack = []
    
            for token in tokens:
                if token in self.operators:
                    stack.append(self.operators[token](stack.pop(), stack.pop()))
                else:
                    stack.append(int(token))
    
            return stack[0]

  • 0
    H

    Thanks for this solution. What tripped me up the most was that I didn't use operator.truediv. Your solution is very elegant.


  • 0
    K

    What a trick and elegant method !
    Thanks a lot .


  • 0
    O

    Nice mann Thanks! "y, x part" is cooool to fit in stack.pop!


  • 0
    W

    said in A simple Python solution - O(n) 72ms:

    class Solution:
    # @param {string[]} tokens
    # @return {integer}
    def init(self):
    self.operators = {
    '+': lambda y, x: x + y,
    '-': lambda y, x: x - y,
    '*': lambda y, x: x * y,
    '/': lambda y, x: int(operator.truediv(x, y))
    }

    def evalRPN(self, tokens):
        if not tokens:
            return 0
    
        stack = []
    
        for token in tokens:
            if token in self.operators:
                stack.append(self.operators[token](stack.pop(), stack.pop()))
            else:
                stack.append(int(token))
    
        return stack[0]
    

    why you write operators dict in initial rather than in our method or in the class ?


  • 0

    @weiheng4 said in A simple Python solution - O(n) 72ms:

    elf):
    self.operators = {
    '+': lambda y, x: x + y,
    '-': lambda y, x: x - y,
    '*': lambda y, x: x

    So that if evalRPN() is called multiple times, the operators need not be re-initialized each time.


Log in to reply
 

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