Create a gist now

Instantly share code, notes, and snippets.

@dwf /rpn.py
Created Feb 5, 2016

What would you like to do?
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