looping to define a sequence of functions?

R

r.e.s.

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.
 
R

Rainer Deyke

r.e.s. said:
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)]
 
R

r.e.s.

Rainer Deyke said:
r.e.s. said:
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)]

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.
 
P

Peter Abel

r.e.s. said:
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.
.... def fn(x):
.... return x**n
.... return fn
.... .... 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top