How to find all terms in an expression in Sympy

≡放荡痞女 提交于 2019-12-04 18:34:13

问题


I have an expression as: 1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2

What I need is a list that contain the terms in this expression.
i.e. [1/(x+1), 4*x/(x-1), 3, -4*x**2 , 10*x**2]

update: It should not collect like terms. Therefore the list should have -4*x** 2 and 10*x** 2 separately and not 6*x**2 after collecting like terms.


回答1:


Based on the question and comments, if you can get the expression as a string, you can do something like this if you want to avoid term collection.

(sympify("1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2", evaluate=False)).args

this will return all the terms without collecting like terms.




回答2:


The right way to do this is Add.make_args. This is the same things as expr.args from Bjoern's answer, except if the expression is not an Add (a single term), it still gives that term, instead of traversing into that expression.

In [20]: expr = 1/(x+1)+4*x/(x-1)+3-4*x**2

In [21]: print(Add.make_args(expr))
(3, 1/(x + 1), -4*x**2, 4*x/(x - 1))



回答3:


In this case it is very easy:

>>> expr = 1/(x+1)+4*x/(x-1)+3-4*x**2
>>> expr.args
⎛     1        2   4⋅x ⎞
⎜3, ─────, -4⋅x , ─────⎟
⎝   x + 1         x - 1⎠


来源:https://stackoverflow.com/questions/37566132/how-to-find-all-terms-in-an-expression-in-sympy

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