2

I know how to use sympy.utilities.lambdify to parse user-defined functions into lambdas like this:

f = lambdify(('x',), 'x**2 - 4*x')

and I know that I can make it accept a function of t instead using

f = lambdify(('t',), 't**2 - 4*t')

But how do I make it so that lambdify will treat 't' as 'x' in the string, so that 't**2 - 4*t' is treated as identical to 'x**2 - 4*x'? Note that I am not looking for a function of two variables x and t, rather a function of one variable that can parse either letter (but not both!), based on which one shows up in the parsed string. Also note that mixing letters should still be invalid, 't**2 - 4*x' should prefer the ts and ignore the xs.

taylor swift
  • 2,039
  • 1
  • 15
  • 29
  • How about `f = lambdify(('x',), 't**2 - 4*t'.replace('t','x'))`? If that doesn't work for you can you give an example of what it is your trying to do and why? – Dan Jul 06 '16 at 17:43
  • string replacement won’t work because what if the letter `'t'` shows up in a function name? The string `tan(2*t)` will not work. && I am writing a function plotter, and I would like it to accept either `t` or `x` as valid variable names since they are both commonly used in mathematics. – taylor swift Jul 06 '16 at 17:45

1 Answers1

3

I recommend first converting the string to a SymPy expression using sympify.

You can then get the variable(s) from the expression using free_symbols, like

In [1]: (t**2 - 4*t).free_symbols
Out[1]: set([t])
asmeurer
  • 86,894
  • 26
  • 169
  • 240