jeudi 1 mars 2018

Producing combinations of lambda functions compositions

I am facing a challenging issue in order to make my Python3 code more elegant.

Suppose I have a number function with variable number of different inputs, for example something like this:

def fun1(a,b):
    return a+b

def fun2(c,d,e):
    return c*d + e

def fun3(x):
    return x*x

These functions needs to be agglomerated in a single function that needs to be used as the optimization function of a numerical solver.

However I need to create different combinations of various operations with these functions, like for example multiplying the output of the first two functions and summing by the third.

The manual solution is to create a specific lambda function:

fun = lambda x : fun1(x[0],x[1])*fun2(x[2],x[3],x[4]) + fun3(x[4])

but the number of functions I have is large and I need to produce all the possibile combinations of them. I would like to systematically be able to compose these functions and always knowing the mapping from the arguments of higher level function fun to the lower level arguments of each single function. In this case I manually specified that x[0] corresponds to the argument a of fun1, x[1] corresponds to argument b of fun1 etcetera.

Any idea?

Aucun commentaire:

Enregistrer un commentaire