pythonsympylambdify

lambdify sympy with Variable-Length Arguments


I have a list of expr with a different number of variables as follows:

G = [[-x_1 + y_1], [-x_2 + y_1 + y_2], [y_1 + y_2] , [-y_3] , ....]

I want to evaluate these expressions using sympy and lambdify. For this purpose, I have written the following instructions:

def f(item):
    return lamndify(list(tem.free_symbols), item)



for  item in G:
    f_ = f(item)
    ...

Now, what should I do to call f_ because there are different variables in each term?


Solution

  • Get the pertinent free_symbols, too. Perhaps make your function return those for you or else recapture them:

    def f(item):
        return lambdify(list(item.free_symbols), item)
    def f2(item):
        args = list(item.free_symbols)
        return args, lambdify(args, item)
    
    for [gi] in G:
        args = list(gi.free_symbols)
        f_ = f(gi)
        a, f2_ = f2(gi)
        assert f_(*args) == f2_(*a)
    

    If you have a set of values you want to use like vals = {x_1:1,x_2:2,y_1:3,y_2:4,y_3:5} then something like this could be used:

    >>> for [gi] in G:
    ...     a, f2_ = f2(gi)
    ...     v = [vals[i] for i in a]
    ...     print(v, f2_(*v))
    ...
    [3, 1] 2
    [3, 2, 4] 5
    [3, 4] 7
    [5] -5