Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def evalRPN(self, tokens: List[str]) -> int:
- """ Approach: Step through the input while adding the numbers to a stack,
- and if you come to a point where the
- current entry is an operator, pop the last two entries and perform the
- operation, and then add the result back onto the stack.
- """
- stack = []
- for t in tokens:
- if t not in {'+', '-', '*', '/'}:
- stack.append(int(t))
- else:
- second_operand = stack.pop()
- first_operand = stack.pop()
- if t == '+':
- stack.append(first_operand + second_operand)
- elif t == '-':
- stack.append(first_operand - second_operand)
- elif t == '*':
- stack.append(first_operand * second_operand)
- elif t == '/':
- stack.append(int(first_operand / second_operand))
- return stack.pop()
Advertisement
Add Comment
Please, Sign In to add comment