Skip to content

Instantly share code, notes, and snippets.

@viebel
Last active September 22, 2016 14:21
Show Gist options
  • Save viebel/3d0f146484989b0c5afc29e53e3e9f2c to your computer and use it in GitHub Desktop.
Save viebel/3d0f146484989b0c5afc29e53e3e9f2c 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:
stack.append(int(token))
return stack.pop()
print(eval("1 2 + "))
print(eval("990 1 2 + *"))
print(eval("1000 990 1 2 + * +"))
@gardyna
Copy link

gardyna commented Sep 22, 2016

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