Xyz-47
Xyz-47

Reputation: 363

Extract terms of an expression

Is there a sympy function that extracts all terms of an equation of Add , Mul and Div expressions, as a list or set?

For example:

(x**2 +(x-1)*ln(x)+(x+2)/(x-1))

I want to get :

[x**2,(x+1)*ln(x),(x+2)/(x-1)]

same thing with Mul:

(x-1)*ln(x) : [(x-1),ln(x)]

and Divison:

(x+2)/(x-1) : [x+2,x-1]

Upvotes: 3

Views: 1887

Answers (1)

asmeurer
asmeurer

Reputation: 91490

For a sum or product, you can use expr.args:

In [1]: ((x**2 +(x-1)*ln(x)+(x+2)/(x-1))).args
Out[1]:
⎛ 2  x + 2                ⎞
⎜x , ─────, (x - 1)⋅log(x)⎟
⎝    x - 1                ⎠

In [2]: ((x-1)*ln(x)).args
Out[2]: (x - 1, log(x))

For a division, SymPy represents x/y as x*y**-1 (there is no division class, only Mul and Pow).

In [3]: ((x+2)/(x-1)).args
Out[3]:
⎛  1         ⎞
⎜─────, x + 2⎟
⎝x - 1       ⎠

However, you can use fraction to split it

In [4]: fraction((x+2)/(x-1))
Out[4]: (x + 2, x - 1)

Upvotes: 5

Related Questions