Reputation: 11657
Suppose I have a list of functions
f1(x,y),f2(x,y),....
How can I define the function below:
z(x,y)=f1(x,y)+f2(x,y)+...
I want to be able to specify x later. So if somebody puts the y=c value, I want the z function to become a function of x! In the simple case when you you have one function, f, and you want to make f(x,y) to be a function of x only by specifying y=c you can use:
z=lambda x:f(x,c)
but the thing is such a method won't work for more than one function!
Upvotes: 0
Views: 261
Reputation: 711
Tweaking the previous answers, we can throw in functools.partial
to create the desired behavior.
We can do a partial function call (similar to the haskell construct) to produce new functions from incompletely applied functions. Check it out:
from functools import partial
funcs = [lambda x, y: x + y] * 10 # a list of ten placeholder functions.
def z(functions, x, y):
return sum(f(x, y) for f in functions)
a = partial(z, funcs, 1)
# 'a' is basically the same as: lambda y: z(funcs, 1, y)
print a # <functools.partial object at 0x7fd0c90246d8>
print a(1) # 20
print a(2) # 30
print a(3) # 40
More here: http://docs.python.org/2/library/functools.html#functools.partial
Upvotes: 2
Reputation: 11046
What if you have other arbitrary functions? What if you want to sum any old number of functions?
def funcSum(x, y, *funcs):
return sum((func(x,y) for func in funcs))
funcSum(x, y, f, g, h)
Arbitrary numbers of arguments gets a little more complex...
Upvotes: 1
Reputation: 98078
Can be useful for 10s of functions:
def z(x,y,functions):
return sum(F(x,y) for F in functions)
So you can use it like:
z(x,y,(f,g,h))
Or if the number of functions comes from a list:
z(x,y,list_of_functions)
Upvotes: 5
Reputation: 2428
Assuming you have your functions in a list functions
:
z = lambda x, y : sum((f(x, y) for f in functions))
Upvotes: 2