Last active
September 22, 2016 14:21
-
-
Save viebel/3d0f146484989b0c5afc29e53e3e9f2c to your computer and use it in GitHub Desktop.
reverse polish evaluator in python
This file contains 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
# This example assumes binary operators, but this is easy to extend. | |
# Comes from this excellent article: http://blog.reverberate.org/2013/07/ll-and-lr-parsing-demystified.html | |
ops = { | |
"+": (lambda a, b: a + b), | |
"-": (lambda a, b: a - b), | |
"*": (lambda a, b: a * b), | |
"/": (lambda a, b: a / b) | |
} | |
def eval(expression): | |
tokens = expression.split() | |
stack = [] | |
for token in tokens: | |
if token in ops: | |
arg2 = stack.pop() | |
arg1 = stack.pop() | |
result = ops[token](arg1, arg2) | |
stack.append(result) | |
else: | |
stack.append(int(token)) | |
return stack.pop() | |
print(eval("1 2 + ")) | |
print(eval("990 1 2 + *")) | |
print(eval("1000 990 1 2 + * +")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
due to this:
http://stackoverflow.com/questions/8758612/can-i-make-a-pull-request-on-a-gist-on-github
I have an updated version here (only changed one word):
https://gist.github.com/gardyna/ff41e861f6e784b9d3f34d2cea35140d