[Tutor] A little math and Python: rpn was: Horner's rule
Gregor Lingl
glingl@aon.at
Thu, 22 Aug 2002 02:01:30 +0200
Gregor Lingl schrieb:
>
> 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]) )
>
Maybe this one is clearer:
# evaluation of an rpn-string
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 ["+", "-", "*", "/"]:
num1, num2, op = lst[0:1], lst[1:-1], lst[-1]
else:
num1, num2, op = lst[:-2], lst[-2:-1], lst[-1]
return str(eval (rpnr(num1,trace) + op + rpnr(num2,trace)) )