How to split a sum into its parts without converting to string in python

纵饮孤独 提交于 2019-12-11 17:08:05

问题


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.

What could I do to split the multivariate polynomial into the monomial parts without first converting the expression to a string?


回答1:


You can explore a sympy expression using .func and .args:

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:

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:

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


来源:https://stackoverflow.com/questions/45126448/how-to-split-a-sum-into-its-parts-without-converting-to-string-in-python

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