leetcode/0150_evaluate-reverse-polish-notation/python3/solution.py

25 lines
651 B
Python
Raw Normal View History

2022-04-12 23:25:09 +00:00
import math
from collections import deque
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
compute = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: math.trunc(a / b)
}
stack = deque()
for token in tokens:
if token.lstrip('-').isdigit():
stack.append(int(token))
else:
right = stack.pop()
left = stack.pop()
stack.append(compute[token](left, right))
return stack[-1]