Help- Recursion v. Iter Speed comparison

actuary77 actuary77 at elemental-systems.com
Thu Mar 3 17:19:05 EST 2005


Robert Kern wrote:
> actuary77 wrote:
> 
>> #================================================
>> #  non-generator
>> #================================================
>>
>>
>> def f1(afunc,aseed,n):
>>     values = [afunc(aseed)]
>>     for i in range(n-1):
>>         values.append(afunc(values[-1]))
>>     return values[-1]
>>
>> _b=time()
>> for _i in range(0,100):
>>     _y = f1(myfunc,seed,n)
> 
> 
> Why do you do this? The whole point of this approach was to keep the 
> intermediate results instead of recomputing them every time!
>
The point is to get some meaningful results when "timing" the function.


> And why do you prepend underscores everywhere? It's bad Python style.

I prepend underscore to differentiate local,private variables vs. global 
variables.  Do not want to create a conflict.  It is my understanding 
that this is the Python style for local v. global variables.


> 
>> _e=time()
>> _t=_e-_b
>>
>> print "f1 result: %r time: %f\n" % (_y,_t*10000.)
>>
>>
>> #================================================
>> #  generator
>> #================================================
>>
>> def f2(afunc,aseed,n):
>>     v = myfunc(aseed)
>>     print v
>>     for i in range(n):
>>         yield v
>>         v = afunc(v)
>>
>> def f2gen(i):
>>     for _i in range(1,n-1):
>>         f2(myfunc,seed,n)
>>     return f2(myfunc,seed,n)
>> _b=time()
>> for _i in range(0,cnt):
>>     _y = f2gen(_i)
>> _e=time()
>> _t=_e-_b
>> print "f2gen result: %r time: %f\n" % (_y,_t*10000.)
>>
>>
>> ==>
>>
>> rec result: 10.005049999999988 time: 47669.999599
>>
>> f1 result: 10.004999999999988 time: 399.999619
>>
>> f2gen result: <generator object at 0x008D74E0> time: 30739.998817
>>
>> I don't know how to get the generator to work correcly, I understand 
>> that the yield preserves the state of the funcion every time it is 
>> called. So in order to have myfunc called 50 times, the generator must 
>> be called 50 times, but it refuses to return a value.  PEP 255 isn't 
>> helping me.
> 
> 
> No, the generator call creates a generator object which you iterate over.
> 
>   for value in f2(myfunc, seed, n):
>       print value
> 
> If you absolutely need a list:
> 
>   list(f2(myfunc, seed, n))
> 

Thank you.



More information about the Python-list mailing list