Rastapopoulos
Rastapopoulos

Reputation: 507

Find functions in sympy expression

I am looking for a robust way of finding functional parameters in a Sympy expression. For example, in the example below, how can one retrieve f from operator?

import sympy

x, y = sympy.symbols('x y')
f = sympy.Function('f')
operator = x*f(x, y).diff(x) + y*f(x, y)

print(operator.free_symbols)
# prints {x, y}

Upvotes: 6

Views: 1077

Answers (1)

user6655984
user6655984

Reputation:

The method expr.atoms(class) returns the set of all objects in expr that are instances of that class. So,

operator.atoms(sympy.Function)

will return f(x, y). If you wish to ignore the arguments of the function, use

[a.func for a in operator.atoms(sympy.Function)]

(For a SymPy object a, a.func is its "function" part and a.args is its "arguments" part.)

Note that if operator included, say, sin(x), that would be included by the above code too. To return only undefined (not built-in) functions, replace sympy.Function by sympy.function.AppliedUndef as the class selector in atoms.

Upvotes: 6

Related Questions