Simplify in sympy with custom symbols
Suppose that I have sympy variables x, y
and z
I have the expression (x + y) (x + y) + x
Is it possible that I am able to define z
as x + y
so that I can "simplify" the expression above to z^2 + x
?
That is, I want to use z
wherever I can in the simplified expression.
1 answer

Yes, use
subs
as in>>> var('x:z') (x, y, z) >>> ((x + y)*(x + y) + x).subs(x+y,z) x + z**2
The
subs
routine will sometimes try to be smart about substitutions, but works best when the substitution target is a symbol (and hence unambiguous). So if you want to try the replacementx+y>z
in a more ambiguous expression, try replacingx>zy
, simplify, and then resubstitutezy>x
to restore anything that didn't change:>>> ((x*x + 2 * x * y + y * y) + x).subs(x,zy).expand().subs(zy,x) x + z**2