Skip to content

LC 0150 [M] Evaluate Reverse Polish Notation

Code with Senpai edited this page Mar 24, 2022 · 1 revision
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for x in tokens:
            if x not in '+-*/': # isnumeric() doesn't work for neg numbers (-x)
                stack.append(int(x))
            else:
                op = x
                b = stack.pop()
                a = stack.pop()
                if op == '+':
                    stack.append(a+b)
                elif op == '-':
                    stack.append(a-b)
                elif op == '*':
                    stack.append(a*b)
                elif op == '/':
                    stack.append(int(a/b))
        return stack.pop()
Clone this wiki locally