# Accepted Python solution

• class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack = []
operators = ["+","-","*","/"]
for token in tokens:
if token not in operators:
stack.append(int(token))
else:
if len(stack) < 2:
return False
second = stack.pop()
first = stack.pop()
if token == "+":
result = first + second
elif token == "-":
result = first - second
elif token == "*":
result = first*second
else:
if second == 0:
return False
result = abs(first)/abs(second)
if first*second < 0:
result = -result
stack.append(result)
if len(stack) != 1:
return False
return (stack[0])

• Below is mine:

def evalRPN(self, tokens):
if not tokens:
return None
div = lambda x, y: -(abs(x) / abs(y)) if x * y < 0 else x / y
ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': div}
stack = []
for token in tokens:
if token not in ops:
stack.append(int(token))
else:
right, left = stack.pop(), stack.pop()
stack.append(ops[token](left, right))
return stack[-1]

• this one is so elegant, thanks

• Nice and efficient use of hash table. Minor thing is that I feel your code is fragile and will be broken easily with an invalid input.

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