[Tutor] A little math and Python: rpn was: Horner's rule
Gregor Lingl
glingl@aon.at
Thu, 22 Aug 2002 00:37:44 +0200
Danny Yoo schrieb:
>
>
>It might make an interesting project to write an RPN calculator in Python.
>
>
Do you think of something like this:
def firstopindex(l):
for item in l:
if item in ["+","-","*","/"]: return l.index(item)
def rpn(inpstr, trace=0):
return rpnr(inpstr.split(), trace)
def rpnr(s, trace):
if trace: print s
if len(s) == 1: return s[0]
i = firstopindex(s)
return rpnr(s[:i-2]+[str(eval(s[i-2]+s[i]+s[i-1]))] + s[i+1:], trace)
>>> rpn("1 2 3 4 5 6 + - + 100 * + +")
'-397'
>>> rpn("1 2 3 4 5 6 + - + 100 * + +", 1)
['1', '2', '3', '4', '5', '6', '+', '-', '+', '100', '*', '+', '+']
['1', '2', '3', '4', '11', '-', '+', '100', '*', '+', '+']
['1', '2', '3', '-7', '+', '100', '*', '+', '+']
['1', '2', '-4', '100', '*', '+', '+']
['1', '2', '-400', '+', '+']
['1', '-398', '+']
['-397']
'-397'
quick and dirty late night divertimento!
Gregor