nathanwailes

LeetCode 150 - Evaluate Reverse Polish Notation - 2023.10.29 solution

Oct 29th, 2023
1,017
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. class Solution:
  2.     def evalRPN(self, tokens: List[str]) -> int:
  3.         """ Approach: Step through the input while adding the numbers to a stack,
  4.        and if you come to a point where the
  5.        current entry is an operator, pop the last two entries and perform the
  6.        operation, and then add the result back onto the stack.
  7.        """
  8.         stack = []
  9.  
  10.         for t in tokens:
  11.             if t not in {'+', '-', '*', '/'}:
  12.                 stack.append(int(t))
  13.             else:
  14.                 second_operand = stack.pop()
  15.                 first_operand = stack.pop()
  16.                 if t == '+':
  17.                     stack.append(first_operand + second_operand)
  18.                 elif t == '-':
  19.                     stack.append(first_operand - second_operand)
  20.                 elif t == '*':
  21.                     stack.append(first_operand * second_operand)
  22.                 elif t == '/':
  23.                     stack.append(int(first_operand / second_operand))
  24.        
  25.         return stack.pop()
  26.  
Advertisement
Add Comment
Please, Sign In to add comment