Skip to content

Instantly share code, notes, and snippets.

@dwf
Created February 5, 2016 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwf/ae7b249bcd24d5b9aafe to your computer and use it in GitHub Desktop.
Save dwf/ae7b249bcd24d5b9aafe to your computer and use it in GitHub Desktop.
A reverse Polish notation calculator in 50 lines.
"""A reverse Polish notation calculator. Supports float and int literals."""
from __future__ import print_function
import operator
import sys
OPERATORS = {'+': operator.add, '-': operator.sub, '%': operator.mod, '/':
operator.truediv, '//': operator.floordiv, '*': operator.mul,
'**': operator.pow}
def recognize_numeric(token):
"""Recognize int and float literals. Return None if it's neither."""
if token.isnumeric():
return int(token)
else:
try:
return float(token)
except ValueError:
return None
def parse_rpn(expr):
"""Execute reverse Polish notation arithmetic. ValueError on bad parse."""
stack = []
for token in expr.split():
result = recognize_numeric(token)
if result is None:
try:
b, a = stack.pop(), stack.pop()
result = OPERATORS[token](a, b)
except (KeyError, IndexError):
raise ValueError
stack.append(result)
if len(stack) > 1:
raise ValueError
return stack.pop()
if __name__ == "__main__":
while True:
print("> ", end="")
try:
expr = input()
except EOFError:
print('Bye')
sys.exit(0)
try:
print(parse_rpn(expr))
except ValueError:
print('Invalid parse')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment