Python Development, memoized functions.

Antti Karttunen antti.karttunen at gmail.com
Fri Jan 5 00:19:38 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.
>
What will happen when you call A000045 multiple times, with varying n 
(increasing and decreasing
at times)?

-- Antti

> Alec
>
>
>
>






More information about the SeqFan mailing list