[Tutor] Simple RPN calculator

Andreas Kostyrka andreas at kostyrka.org
Mon Dec 6 20:03:52 CET 2004


Am Mo, den 06.12.2004 schrieb Chad Crabtree um 14:05:
> 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.
Well, I'm down to 12 lines:
import operator, sys
st = []
while 1:
    s = raw_input("%s>" % [str(x) for x in st]).split()
    if not s: break
    for t in s:
        func = {'+':operator.add, '-':operator.sub, '*':operator.mul,
'/':operator.div}.get(t, None)
        if func is None:
            st.append(float(t))
        else:
            sec = st.pop()
            fir = st.pop()
            st.append(func(fir, sec))

Andreas
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20041206/5fe2150f/attachment.pgp


More information about the Tutor mailing list