[Tutor] A little math and Python: rpn was: Horner's rule
Gregor Lingl
glingl@aon.at
Thu, 22 Aug 2002 01:20:45 +0200
Gregor Lingl schrie
>
> 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)
>
> quick and dirty late night divertimento!
>
> Gregor
>
Suddenly I had the feeling: "What a fool I was!", because I didn't make
use of the recursive nature of the stack which is built ba the
rpn-calculator.
I tried to find a better solution:
def rpn(inpstr, trace=0):
return rpnr(inpstr.split(), trace)
def rpnr(lst, trace):
if trace: print lst
if len(lst) == 1: return lst[0]
if lst[-2] in ["+", "-", "*", "/"]:
return str( eval( lst[0] +lst[-1] + rpnr(lst[1:-1],trace)) )
else:
return str( eval( rpnr(lst[:-2],trace) + lst[-1] + lst[-2]) )
>>> rpn(s,1)
['1', '2', '3', '*', '+']
['2', '3', '*']
['2']
'7'
>>> rpn("1 2 3 4 5 6 + - + 100 * + +", 1)
['1', '2', '3', '4', '5', '6', '+', '-', '+', '100', '*', '+', '+']
['2', '3', '4', '5', '6', '+', '-', '+', '100', '*', '+']
['3', '4', '5', '6', '+', '-', '+', '100', '*']
['3', '4', '5', '6', '+', '-', '+']
['4', '5', '6', '+', '-']
['5', '6', '+']
['5']
'-397'
>>>
Now, I feel still not fully satisfied!
But it's too late to continue now
Best wishes, Gregor