Forked from viebel/reverse_polish_evaluator.py
Last active
September 28, 2019 06:20
-
-
Save gardyna/ff41e861f6e784b9d3f34d2cea35140d 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: | |
# if it's not an operator it's a number | |
stack.append(float(token)) | |
return stack.pop() | |
print(eval("1 2 + ")) | |
print(eval("990 1 2 + *")) | |
print(eval("1000 990 1 2 + * +")) | |
print(eval("1000 990.4 1 2 + * +")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
float for a more general case