Simplify expression

I have expressions like:

a*b*c + d*e + f - g*h*h + i*a

In other words: terms can either be added or subtracted, and each term is a product of some characters.

Is there a way to come up with a minimal / simpler expression, mostly the other way around? I tried simplifyand factorbut I can not get them to work. For example:

a**4 - 4*a**3*b + 6*a**2*b**2 - 4*a*b**3 - a + b**4

should turn into:

(a - b)**4 - a

but when using these commands, it remains unchanged.

PS: If this is something that Sympy cannot do, could you suggest an alternative that does this?

+4
source share
2 answers

. SymPy factor , , , , subs, :

>>> expr = a**4 - 4*a**3*b + 6*a**2*b**2 - 4*a*b**3 - a + b**4
>>> expr.subs(a, x + b).expand()
-b + x**4 - x
>>> expr.subs(a, x + b).expand().subs(x, a - b)
-a + (a - b)**4

, x = a - b, a = x + b. a x + b, .

SymPy , a*b :

>>> expr = (a*b - c*d)**2 - a
>>> expr = expr.expand()
>>> expr
a**2*b**2 - 2*a*b*c*d - a + c**2*d**2
>>> expr.subs(a*b, x + c*d)
-a + c**2*d**2 - 2*c*d*(c*d + x) + (c*d + x)**2
>>> expr.subs(a*b, x + c*d).expand()
-a + x**2
>>> expr.subs(a*b, x + c*d).expand().subs(x, a*b - c*d)
-a + (a*b - c*d)**2

(itertools.combinations ). , , :

>>> args = Add.make_args(expr)
>>> for comb in combinations(args, len(args) - 1):
...    print(factor(Add(*comb)) + Add(*(set(args) - set(comb))))
...
a**4 - 4*a**3*b + 6*a**2*b**2 - 4*a*b**3 - a + b**4
a**4 - 4*a**3*b + 6*a**2*b**2 - 4*a*b**3 - a + b**4
a**4 - 4*a**3*b + 6*a**2*b**2 - 4*a*b**3 - a + b**4
a**4 - 4*a**3*b + 6*a**2*b**2 - 4*a*b**3 - a + b**4
-a + (a - b)**4
a*(a**3 - 4*a**2*b + 6*a*b**2 - 4*b**3 - 1) + b**4

not isinstance(factored_expr, Add), , .

+1

, , Maple, , . Maple , , . .

, , . Maple Mathematica, ( ) , maxima. http://maxima.sourceforge.net/

+1

Source: https://habr.com/ru/post/1531157/


All Articles