Last active
August 29, 2015 14:00
-
-
Save rioshen/5c938e7ce67d96f1bb2e to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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