Sympy: Get functions from expression

南笙酒味 提交于 2019-12-23 12:55:06

问题


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?


回答1:


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)])



回答2:


atoms does the trick:

for f in y.atoms(Function):
    print(f.func)


来源:https://stackoverflow.com/questions/36594508/sympy-get-functions-from-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!