looping to define a sequence of functions?

r.e.s. r.s at ZZmindspring.com
Tue Jan 6 14:57:11 EST 2004


"Rainer Deyke" <rainerd at eldwood.com> wrote ...
> r.e.s. wrote:
> > 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.)
> 
> functions = [lambda x, n=n: x**n for n in range(10)]
> 
> -or-
> 
> class X(object):
>   def __init__(self, n):
>     self.n = n
>   def __call__(self, x):
>     return x ** self.n
> functions = [X(n) for n in range(10)]
> 
> -or-
> 
> functions = []
> for n in range(10):
>   def f(x, n=n):
>     return x**n
>   functions.append(f)
> 
> -or-
> 
> def create_function(n):
>   def f(x):
>     return x**n
>   return f
> functions = [create_function(n) for n in range(10)]
> 
> 
> -- 
> Rainer Deyke - rainerd at eldwood.com - http://eldwood.com

It's going to take me a bit to digest these, and
it looks like I'm sure to learn from them, so I 
want to say 'thank you' now for the quick reply.



More information about the Python-list mailing list