I have a variety of SymPy expressions involving UndefinedFunction instances:
我有各种涉及UndefinedFunction实例的SymPy表达式:
f = Function('f')
g = Function('g')
e = f(x) / g(x)
How can I obtain a list of the function invocations appearing in such expressions? In this example, I'd like to get [f(x), g(x)]
.
如何获取此类表达式中出现的函数调用列表?在这个例子中,我想得到[f(x),g(x)]。
I'm aware of free_symbols
but it kicks back set([x])
(as it should).
我知道free_symbols但是它会踢回set([x])(就像它应该的那样)。
2 个解决方案
#1
3
You are right that you want to use atoms
, but be aware that all functions in SymPy subclass from Function
, not just undefined functions. So you'll also get
你想要使用原子是正确的,但要注意SymPy中的所有函数都是来自Function的子类,而不仅仅是未定义的函数。所以你也会得到
>>> (sin(x) + f(x)).atoms(Function)
set([f(x), sin(x)])
So you'll want to further reduce your list to only those functions that are UndefinedFunction
s. Note that UndefinedFunction
is the metaclass of f
, so do to this, you need something like
因此,您需要进一步将列表缩小为仅包含UndefinedFunctions的函数。请注意,UndefinedFunction是f的元类,所以要做到这一点,你需要类似的东西
>>> [i for i in expr.atoms(Function) if isinstance(i.__class__, UndefinedFunction)]
[f(x)]
#2
1
It turns out that the atoms
member method can accept a type on which to filter. So
事实证明,atoms成员方法可以接受要过滤的类型。所以
e.atoms(Function)
returns
回报
set([f(x), g(x)])
as I'd wanted. And that fancier things like
就像我想要的那样。还有更高级的东西
e.diff(x).atoms(Derivative)
are possible.
是可能的。
#1
3
You are right that you want to use atoms
, but be aware that all functions in SymPy subclass from Function
, not just undefined functions. So you'll also get
你想要使用原子是正确的,但要注意SymPy中的所有函数都是来自Function的子类,而不仅仅是未定义的函数。所以你也会得到
>>> (sin(x) + f(x)).atoms(Function)
set([f(x), sin(x)])
So you'll want to further reduce your list to only those functions that are UndefinedFunction
s. Note that UndefinedFunction
is the metaclass of f
, so do to this, you need something like
因此,您需要进一步将列表缩小为仅包含UndefinedFunctions的函数。请注意,UndefinedFunction是f的元类,所以要做到这一点,你需要类似的东西
>>> [i for i in expr.atoms(Function) if isinstance(i.__class__, UndefinedFunction)]
[f(x)]
#2
1
It turns out that the atoms
member method can accept a type on which to filter. So
事实证明,atoms成员方法可以接受要过滤的类型。所以
e.atoms(Function)
returns
回报
set([f(x), g(x)])
as I'd wanted. And that fancier things like
就像我想要的那样。还有更高级的东西
e.diff(x).atoms(Derivative)
are possible.
是可能的。