Open parenthesis of sympy Mul

Question:

I have the following expression multiplying two expressions:

from sympy import *
c1, c2, x = symbols("c1, c2, x")
expr = c2*x*(c1*x + c2*x)

I would like to be able to open the parenthesis, so that this expression would be

c1*c2*x**2 + c2**2*x**2

I need this because I want to analyze each monom separately
How can this be done? I tried converting it to Poly and back, but for some reason it causes errors non-deterministically.

Asked By: Shaharg

||

Answers:

It sounds like you just want to use expand:

In [1]: from sympy import *
   ...: c1, c2, x = symbols("c1, c2, x")
   ...: expr = c2*x*(c1*x + c2*x)

In [2]: expr
Out[2]: c₂⋅x⋅(c₁⋅x + c₂⋅x)

In [3]: expr.expand()
Out[3]: 
       2     2  2
c₁⋅c₂⋅x  + c₂ ⋅x 

Poly should also work and should be deterministic (I suspect you have made some other error if you think it is non-deterministic):

In [4]: Poly(expr)
Out[4]: Poly(x**2*c1*c2 + x**2*c2**2, x, c1, c2, domain='ZZ')

In [5]: Poly(expr).as_expr()
Out[5]: 
       2     2  2
c₁⋅c₂⋅x  + c₂ ⋅x 

You can also get a mapping of monomials and coefficients without converting to Poly using as_coefficients_dict:

In [6]: dict(expr.expand().as_coefficients_dict())
Out[6]: 
⎧  2  2            2   ⎫
⎨c₂ ⋅x : 1, c₁⋅c₂⋅x : 1⎬
⎩                      ⎭
Answered By: Oscar Benjamin