[LeetCode] Evaluate Reverse Polish Notation (Python)

2024. 3. 6. 14:10자료구조

 

 

import math

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        operation = ["+", "-", "*", "/"]
        stack = []
        
        if len(tokens) == 1: 
            return int(tokens[0])
        for i in range(len(tokens)):
            if tokens[i] not in operation:
                stack.append(int(tokens[i]))
            else:
                num1 = stack.pop()
                num2 = stack.pop()
                new_num = 0
                if tokens[i] == "+":
                    new_num = num2 + num1
                elif tokens[i] == "-":
                    new_num = num2 - num1
                elif tokens[i] == "*":
                    new_num = num2 * num1
                else:
                    new_num = num2 / num1
                    new_num = math.trunc(new_num)
                stack.append(new_num)
        return stack.pop()