Suppose I have some expression
假设我有一些表达方式
from sympy import *
a,b,c,x,y = symbols('a c b x y')
eq=a*x + b*x*y + c*y**2
that needs to be split into an array containing the monomials.
需要将其拆分为包含单项式的数组。
The current solution I have is
我目前的解决方案是
parts = str(eq).split(' + ')
Then, I use the eval function on each element of the array parts to be interpreted as an expression.
然后,我在数组部分的每个元素上使用eval函数来解释为表达式。
What could I do to split the multivariate polynomial into the monomial parts without first converting the expression to a string?
如何在不先将表达式转换为字符串的情况下将多元多项式分割为单项式部分,我该怎么办?
1 个解决方案
#1
0
You can explore a sympy
expression using .func
and .args
:
您可以使用.func和.args探索一个sympy表达式:
eq.func
> <class 'sympy.core.add.Add'>
eq.args
> (a*x, b*y**2, c*x*y)
Each of these args are again sympy
expressions and can be explored in the same way:
这些args中的每一个都是同情表达,可以用同样的方式进行探索:
eq.args[0].func
> <class 'sympy.core.mul.Mul'
eq.args[0].args
> (a, x)
And so on. Note that at the final levels of the expression tree you will need other functions than .func
and .args
, for example:
等等。请注意,在表达式树的最终级别,您将需要除.func和.args之外的其他函数,例如:
eq.args[0].args[0].name # the a in a*x
> 'a'
eq.args[1].args[1].args[1].n() # the 2 in y**2
> 2.00000000000000
#1
0
You can explore a sympy
expression using .func
and .args
:
您可以使用.func和.args探索一个sympy表达式:
eq.func
> <class 'sympy.core.add.Add'>
eq.args
> (a*x, b*y**2, c*x*y)
Each of these args are again sympy
expressions and can be explored in the same way:
这些args中的每一个都是同情表达,可以用同样的方式进行探索:
eq.args[0].func
> <class 'sympy.core.mul.Mul'
eq.args[0].args
> (a, x)
And so on. Note that at the final levels of the expression tree you will need other functions than .func
and .args
, for example:
等等。请注意,在表达式树的最终级别,您将需要除.func和.args之外的其他函数,例如:
eq.args[0].args[0].name # the a in a*x
> 'a'
eq.args[1].args[1].args[1].n() # the 2 in y**2
> 2.00000000000000