Skip to content

Instantly share code, notes, and snippets.

@slackorama
Created April 2, 2012 05:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save slackorama/2281116 to your computer and use it in GitHub Desktop.
Save slackorama/2281116 to your computer and use it in GitHub Desktop.
Python implementation of an RPN calculator
#!/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.div
}
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 = raw_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
@Henner365
Copy link

i have an adjusted version compiling under 3.6.5.

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