[Tutor] Simple RPN calculator

Bob Gailer bgailer at alum.rpi.edu
Mon Dec 6 23:03:07 CET 2004


At 06:05 AM 12/6/2004, you wrote:
>Bob Gailer wrote:
>
> > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input
> > and prints -0.0481481.... 8 lines of Python. That indeed is less than
> > 100. Took about 7 minutes to code and test.
>
>I'm quite interested in seeing the sourcecode for that.

I've made it interactive (enter an operand or operator and hit enter); it 
displays the top of the stack. I added . ^ and %. No error checking.

import operator as op
def rpn(o,stack = [],d = {'*':op.mul, '+':op.add, '/':op.truediv, 
'%':op.mod, '-':op.sub, '^':op.pow, '.':lambda x,y:x+.1*y}):
   if o in d: stack[-2:] = [d[o](stack[-2], stack[-1])]
   elif o: stack.append(float(o)) # could bomb here if input not floatable!
   else: return 1
   print stack[-1]
while 1:
   if rpn(raw_input('>')): break

Let me know what you think.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell  



More information about the Tutor mailing list