Question - What is a faster alternative to recursion?
actuary77
actuary77 at elemental-systems.com
Wed Mar 2 01:58:58 EST 2005
Heiko Wundram wrote:
> On Wednesday 02 March 2005 06:03, actuary77 wrote:
>
>>It now makes sense if I write it, (simple):
>>
>>def rec2(n):
>> if n == 0:
>> return []
>> else:
>> return [n] + rec2(n-1)
>
> Or, if you're not interested in a recursive function to do this job (which
> should be way faster...):
>
>
>>>>def iter1(n):
>
> ... nl = range(1,n+1)
> ... nl.reverse()
> ... return nl
> ...
>
>>>>print iter1(4)
>
> [4, 3, 2, 1]
>
>
Yes, iteration is 10000000000 times faster than recursion.
The problem I have is:
# need to call this function 50 times with seed of 10
(afunc(afunc(afunc(... afunc(10))
required_iterations_ 50
function: afunc(x): x**.5 + 1000 * x + 46.
initial_seed: 10
Result => afunc(afunc(afunc(afunc(afunc(afunc ... (_aseed)
What is the fastest way to do this without using recursion?
With recursion:
================
def rec(afunc,n,x):
y = afunc(x)
if n == 0:
return y
else:
return rec(afunc,n-1,y)
def myfunc(x):
return x**.5 + 1000 * x + 46.
from time import time
_b=time()
_y = rec(myfunc,50,10)
_e=time()
_t=_e-_b
print "result: %r time: %f\n" % (_y,_t)
output:
result: 1.00493118428005e+154 time: 0.030000
Is there a much faster way?
More information about the Python-list
mailing list