# A simple Python solution - O(n) 72ms

• ``````class Solution:
# @param {string[]} tokens
# @return {integer}
def __init__(self):
self.operators = {
'+': lambda y, x: x + y,
'-': lambda y, x: x - y,
'*': lambda y, x: x * y,
'/': lambda y, x: int(operator.truediv(x, y))
}

def evalRPN(self, tokens):
if not tokens:
return 0

stack = []

for token in tokens:
if token in self.operators:
stack.append(self.operators[token](stack.pop(), stack.pop()))
else:
stack.append(int(token))

return stack[0]``````

• Thanks for this solution. What tripped me up the most was that I didn't use `operator.truediv`. Your solution is very elegant.

• What a trick and elegant method !
Thanks a lot .

• Nice mann Thanks! "y, x part" is cooool to fit in stack.pop!

• class Solution:
# @param {string[]} tokens
# @return {integer}
def init(self):
self.operators = {
'+': lambda y, x: x + y,
'-': lambda y, x: x - y,
'*': lambda y, x: x * y,
'/': lambda y, x: int(operator.truediv(x, y))
}

``````def evalRPN(self, tokens):
if not tokens:
return 0

stack = []

for token in tokens:
if token in self.operators:
stack.append(self.operators[token](stack.pop(), stack.pop()))
else:
stack.append(int(token))

return stack[0]
``````

why you write operators dict in initial rather than in our method or in the class ?

• elf):
self.operators = {
'+': lambda y, x: x + y,
'-': lambda y, x: x - y,
'*': lambda y, x: x

So that if evalRPN() is called multiple times, the operators need not be re-initialized each time.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.