looping to define a sequence of functions?

Peter Abel PeterAbel at gmx.net
Tue Jan 6 18:39:29 EST 2004


"r.e.s." <r.s at ZZmindspring.com> wrote in message news:<T9EKb.23248$lo3.20297 at newsread2.news.pas.earthlink.net>...
> Suppose we want to define ten functions such that the
> nth function of x simply returns x**n. Is there a way 
> to avoid explicitly writing ten function def's? (They 
> have to be ten distinct functions, not just a single 
> one like def f(n,x): return x**n.)
>  
> E.g., the following doesn't work:
> 
> f = {}
> for n in range(10):
>     def f[n](x):
>         return x**n
> 
> Thanks.

>>> # A parametric factory-function that returns 
>>> # a function depending on the parameter n
>>> def factory_function(n):
... 	def fn(x):
... 		return x**n
... 	return fn
... 
>>> # A list of ten different functions
>>> func_list=map(factory_function,range(10))
>>> # And an example of the result with x=2
>>> for i,func in zip(range(len(func_list)),func_list):
... 	print '%2d: %d' % (i,func(2))
... 
 0: 1
 1: 2
 2: 4
 3: 8
 4: 16
 5: 32
 6: 64
 7: 128
 8: 256
 9: 512
>>> 

Regards
Peter



More information about the Python-list mailing list