Python Development, memoized functions.
Jaap Spies
j.spies at hccnet.nl
Fri Jan 5 12:28:52 CET 2007
Alec Mihailovs wrote:
> From: "Antti Karttunen" <antti.karttunen at gmail.com>
>
>> @M
>> def A000045(n): if(n < 2): return(n) else:
>> return(A000045(n-1)+A000045(n-2))
>
>
> Another way of doing this is to define A000045_list first (that saves
> all the calculated values in a list), and then define A000045 as the
> last element of the list. Such as
>
> def A000045_list(n):
> result=[0]
> a,b=0,1
> for i in range(n):
> result.append(b)
> a,b=b,a+b
> return result
>
> def A000045(n): return A000045_list(n)[-1]
>
> That should calculate values faster than the recursive procedure with
> memoization because that avoids multiple function calls.
>
Why not use generators? Make a list large enough,
def fib():
x, y = 0, 1
while 1:
x, y = y, x+y
yield x
f = fib()
a = [f.next() for i in range(1000)]
a.insert(0,0)
def A000045(n):
return a[n]
def A000045_list(N)
return a[:N]
Cheers,
Jaap
More information about the SeqFan
mailing list