Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy: Get functions from expression

Tags:

python

sympy

To get all variables from a sympy expression, one can call .free_symbols on the expression. I would like to retrieve all functions used in an expression. For example, from y in

from sympy import *

f = Function('f')
g = Function('g')

x = Symbol('x')

y = f(x) + 2*g(x)

I'd like to get f and g.

Any hints?

like image 759
Nico Schlömer Avatar asked Dec 25 '22 06:12

Nico Schlömer


2 Answers

atoms does the trick:

for f in y.atoms(Function):
    print(f.func)
like image 176
Nico Schlömer Avatar answered Jan 13 '23 22:01

Nico Schlömer


For all functions, use atoms(Function).

In [40]: (f(x) + sin(x)).atoms(Function)
Out[40]: set([f(x), sin(x)])

For only undefined functions, use atoms(AppliedUndef).

In [41]: from sympy.core.function import AppliedUndef

In [42]: (f(x) + sin(x)).atoms(AppliedUndef)
Out[42]: set([f(x)])
like image 25
asmeurer Avatar answered Jan 13 '23 22:01

asmeurer