Last active
August 29, 2015 14:17
-
-
Save tsmacdonald/bc2c3bc812cb8ae125e2 to your computer and use it in GitHub Desktop.
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
import ast | |
import operator as op | |
import re | |
import sys | |
operators = {'+' : op.add, | |
'-' : op.sub, | |
'*' : op.mul, | |
'/' : op.div} | |
def is_operator(x): | |
return x in operators.keys() | |
def is_number(x): | |
return bool(re.match(r'(\d*\.)?\d+', x)) | |
def eval_rpn(tokens, stack=[]): | |
if not tokens: | |
return stack | |
token = tokens[0] | |
if is_operator(token): | |
rh, lh = stack.pop(), stack.pop() | |
stack.append(operators[token](lh, rh)) | |
return eval_rpn(tokens[1:], stack) | |
elif is_number(token): | |
stack.append(ast.literal_eval(token)) | |
return eval_rpn(tokens[1:], stack) | |
else: | |
raise Exception("Invalid token: %s"%token) | |
if __name__ == "__main__": | |
print eval_rpn(sys.argv[1].split(" ")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment