Search code examples
pythonsympy

Is it possible to apply the distributive property only once


I've been using sympy to help simplify expressions, but at times I would like sympy to only do a limited amount of simplification/expansion.

For example, suppose I have the code:

x = symbols("x")

poly = x*(x**2+x*(x+2))

If I do, expand(poly), I expand to an expression with no parenthesis, but is it possible to apply only the outer distributive property?, i.e., to get just: x^3+x^2(x+2)?

I tried looking at https://docs.sympy.org/latest/tutorials/intro-tutorial/manipulation.html, but it doesn't seem to help.


Solution

  • You can use deep=False:

    In [51]: x = symbols("x")
        ...: 
        ...: poly = x*(x**2+x*(x+2))
    
    In [52]: poly
    Out[52]: 
      ⎛ 2            ⎞
    x⋅⎝x  + x⋅(x + 2)⎠
    
    In [53]: expand_mul(poly, deep=False)
    Out[53]: 
     3    2        
    x  + x ⋅(x + 2)
    

    This example also works with expand but since you are being selective about the manipulation that you want I suggest using expand_mul.