1

Imagine you have the following sympy expression:

'1.0 * H * L * * 3 * W * *2'

which contains the sp.Symbols variables=[H, L and W].

if this expression is lambdify-ed using sp.lambdify([sp.Symbol(vari) for vari in variables],'1.0 * H * L * * 3 * W * *2') you obtain a <function _lambdifygenerated(H, L, W)>.

However, I need to obtain a <function _lambdifygenerated(x)> where H=x[0], L=x[1], and W=x[2].

I have tried to xreplace{H: 'x[0]', W: 'x[1]', L: 'x[2]'} directly on the original expression '1.0 * H * L * * 3 * W * *2' and then lambdify with x as lambda.

This didn't work, but even if it would work after some tries I feel it is not the way to go.

Does anyone have any advice on how to deal with this?

Thank you very much!

adrckul
  • 43
  • 3
  • 1
    This is the beginning of a well-asked question, thank you. It would help if you added some code that we could copy-n-paste, run, see the symptom, tweak, repeat. https://stackoverflow.com/help/minimal-reproducible-example – J_H Oct 26 '22 at 23:21
  • Just write a cover function that takes the `x` and calls the lambdified function. – hpaulj Oct 26 '22 at 23:33

1 Answers1

0

You can preprocess the expression to replace all symbols with an IndexedBase, which you can think of as an array:

from sympy import *
L, H, W = symbols("L H W")
expr = 1.0 * H * L**3 * W**2

variables = [L, H, W]
x = IndexedBase("x")
# substitution dictionary
d = {v: x[i] for i, v in enumerate(variables)}
expr = expr.subs(d)
print(expr)
# out: 1.0*x[0]**3*x[1]*x[2]**2

f = lambdify(x, expr)
import inspect
print(inspect.getsource(f))
# out:
# def _lambdifygenerated(Dummy_22):
#     return 1.0*Dummy_22[0]**3*Dummy_22[1]*Dummy_22[2]**2
Davide_sd
  • 10,578
  • 3
  • 18
  • 30