pythonfunctioncombinationsprogrammatically-created

Creating a function programmatically


There are lots of interesting posts on this subject, but I seem to either not understand their answers, or aiming for something different. Here is what I am trying to do. I have two (or more) functions that I want to combine into a new function. The following snippet shows what I start with, and what I would like to end up with.

def a(x):
    0.2 * x[1] - 0.4 * x[0]

def b(x):
    0.4 * x[0] - 0.2 * x[1]

def ab(x):
    return [0.2 * x[1] - 0.4 * x[0], 0.4 * x[0] - 0.2 * x[1]]

the catch being, that I would like to create ab at run time dynamically. I have a list ml with all functions so I could do the following inside a new function

def abl(x):
    ml = [a, b]
    rl = []
    i = 0
    for f in ml:
        rl.append(f(x[i]))
        i = i + 1 

and then call abl. This code combines the individual functions and results in the expected output. However, for each call to abl rl has to be built anew, which seems wasteful.

Is there another way of combining a and b in order to create a new function ab?


Solution

  • You can dynamically return new functions via lambda expressions:

    def a(x):
        return 0.2 * x[1] - 0.4 * x[0]
    
    def b(x):
        return 0.4 * x[0] - 0.2 * x[1]
    
    def combine(func1, func2):
        return lambda x: [func1(x), func2(x)]
        
    ab = combine(a, b)
    print(ab([1.3, 2.9]))
    

    Output:

    [0.05999999999999994, -0.05999999999999994]