Use stack to cache operand and operator.
In python, 6 / -132 = -1. To get the same result as C division operator, use int( 6 / -132 ) instead.
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
operators = { '+' : lambda a, b: a + b, \
'-' : lambda a, b: a - b, \
'*' : lambda a, b: a * b, \
'/' : lambda a, b: int(a/b) }
for t in tokens:
opt = operators.get(t)
if opt:
b = stack.pop()
a = stack.pop()
c = opt(a, b)
stack.append(c)
else:
stack.append(int(t))
return stack.pop()
Edited on 05/25/2021. Simplify condition checks.
No comments:
Post a Comment