Created
February 5, 2016 07:25
-
-
Save dwf/ae7b249bcd24d5b9aafe to your computer and use it in GitHub Desktop.
A reverse Polish notation calculator in 50 lines.
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
"""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