Skip to content

Instantly share code, notes, and snippets.

@gardyna
Forked from viebel/reverse_polish_evaluator.py
Last active September 28, 2019 06:20
Show Gist options
  • Save gardyna/ff41e861f6e784b9d3f34d2cea35140d to your computer and use it in GitHub Desktop.
Save gardyna/ff41e861f6e784b9d3f34d2cea35140d to your computer and use it in GitHub Desktop.
reverse polish evaluator in python
# 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 + * +"))
@gardyna
Copy link
Author

gardyna commented Sep 22, 2016

float for a more general case

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment