Python Development, memoized functions.

Alec Mihailovs alec at mihailovs.com
Thu Jan 4 23:59:52 CET 2007


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.

Alec








More information about the SeqFan mailing list