-
-
Save Henner365/1a21e75f0ded49fb3230e1e6543dad1b to your computer and use it in GitHub Desktop.
Python implementation of an RPN calculator
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
#!/usr/bin/env python | |
# an rpn calculator in python | |
# > 19 2.14 + 4.5 2 4.3 / - * | |
# [85.297441860465113] | |
# only supports two operands and then an operator | |
import operator | |
ops = { '+': operator.add, | |
'-': operator.sub, | |
'*': operator.mul, | |
'/': operator.truediv | |
} | |
def eval_expression(tokens, stack): | |
for token in tokens: | |
if set(token).issubset(set("0123456789.")): | |
stack.append(float(token)) | |
elif token in ops: | |
if len(stack) < 2: | |
raise ValueError('Must have at least two parameters to perform op') | |
a = stack.pop() | |
b = stack.pop() | |
op = ops[token] | |
stack.append(op(b,a)) | |
else: | |
raise ValueError("WTF? %s" % token) | |
return stack | |
if __name__ == '__main__': | |
stack = [] | |
while True: | |
expression = input('> ') | |
if expression in ['quit','q','exit']: | |
exit() | |
elif expression in ['clear','empty']: | |
stack = [] | |
continue | |
elif len(expression)==0: | |
continue | |
stack = eval_expression(expression.split(), stack) | |
print (stack) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
adjust 4 version 3.6.5.