Skip to content

Instantly share code, notes, and snippets.

@rioshen
Last active August 29, 2015 14:00
Show Gist options
  • Save rioshen/5c938e7ce67d96f1bb2e to your computer and use it in GitHub Desktop.
Save rioshen/5c938e7ce67d96f1bb2e to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
"""Calculates tokens and returns the result.
Use stack to store numbers and pop two numbers once
meets operators then push the calculated result back.
"""
OPS = {
'+': lambda x, y: x+y,
'-': lambda x, y: y-x,
'*': lambda x, y: x*y,
'/': lambda x, y: y/float(x)
}
stack = []
for token in tokens:
if token in OPS:
stack.append(int(OPS[token](stack.pop(), stack.pop())))
else:
stack.append(int(token))
return stack.pop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment