Sympy simplify equation more

66 views Asked by At

I have an expression in sympy like: m*a+m*b+n*a+n*b Which could be simplified to (a+b)*(m+n), but if I run simplify() on it I just get the same expression back. Is there any tricks to make it simplify more?

I have tried using collect(expression, expression.free_symbols) but that at best gets me only to a⋅(m + n) + b⋅(m + n). I have thought about trying to run collect on combinations, but that would get out of hand very quickly since i have a lot more variables in my actual equation and also would have to look for subtractions and more. Is there any better way to do it? Open to suggestions for other libraries also , not fixed on sympy.

2

There are 2 answers

2
smichr On

Use factor instead of simplify; the former is very specific in output while the latter is more general in trying to make the expression "nicer".

>>> from sympy import *
>>> from sympy.abc import a,b,m,n
>>> factor(m*a+m*b+n*a+n*b)
(a + b)*(m + n)
0
ti7 On

Getting too long for a comment on the excellent factor() answer by @smichr, you can be more explicit about how you'd like it factored with collect() if you already know approximately how you'd like the terms

>>> collect(m*a+m*b+n*a+n*b, (m,n))
m*(a + b) + n*(a + b)
>>> collect(m*a+m*b+n*a+n*b+c, (m,n))
c + m*(a + b) + n*(a + b)
>>> collect(m*a+m*b+n*a+n*b+c, (a,c))
a*(m + n) + b*m + b*n + c