lnNoam lnNoam - 1 year ago 78
Python Question

Programmatically define a new function from a list of other functions

I have:

def f(x, y): return x**2 + y**2
def g(x, y): return x**3 + y**3
def h(x, y): return x**4 + y**4

And I'd like to make a new function:

def J(x, y):
return f(x,y)*g(x,y)*h(x,y)

However, I am unable to find a way to do this programmatically.
That is, take something like:

myFunctions = [f,g,h]

and return a new function
which returns the product of

Another wrinkle is that while
will always have an identical number of arguments, that number could change. That is, they could all have could have five arguments instead of two.

Desired behaviour:

print(J(2, 2)) # 4096


The number of functions in
is also arbitrary.
I thought this was implied in my question, but upon rereading it I see that I did not make that at all clear. My apologies.

Answer Source

A function can accept arbitrarily many arguments using * like this:

def J(*args):

This will store all of J's arguments in the list args. That list can then be converted back into multiple arguments to call other functions like this:

def J(*args):
  return f(*args) * g(*args)

This solves the problem of the number of arguments changing. So now let's handle the fact that there can be arbitrarily many functions. First we need to call the function in your list. We can just do that by iterating over them and using ():

def J(*args):
  return [func(*args) for func in myFunctions]

This will return a list of the functions' return values. So all we need now is to get the product of a collection:

from functools import reduce
from operator import mul

def product(numbers):
  return reduce(mul, list, 1)

def J(*args):
  return product(func(*args) for func in myFunctions)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download