Tuesday 6 July 2010

RPN Calculator in Python.

RPN Calculator to solve first Praxis challenge.
http://programmingpraxis.com/2009/02/19/rpn-calculator/

Fairly happy with it, I don't feel right using the in operator to evaluate the token against a string though, it is a bit of a kludge. The first version of this program used a ValueError exception to parse an operator. Although in my heart of hearts I knew this was a bad thing to do it still felt somehow....cleaner.
import sys, operator

def main():
inplist = list(line.split() for line in sys.stdin.readlines())
functions = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}

for expression in inplist:
out = list()
for token in expression:
if token[0] in '01234567890':
out.append(float(token))
else:
rhs = out.pop()
lhs = out.pop()
out.append(functions[token](lhs,rhs))
print out[0]

main()

No comments:

Post a Comment