Sympy's subs limitations
<p>I am working with some long equations but not really complex, and I wanted to use <strong>sympy</strong> to simplify and "factorize" them. But I have encountered a few problems. Here is a list of some minimal examples:</p>

<p><strong>Problem 1: symmetry</strong></p>

<pre><code>from sympy import *
from __future__ import division
a = symbols('a')
b = symbols('b')
expr = 1/12*b + 1
expr.subs(1/12*b, a)
expr.subs(b*1/12, a)
</code></pre>

<p>The first line gives the expected result (ie. <code>a+1</code>) while in the second one there is no substitution.</p>

<p><strong>Problem 2: factorized expressions</strong></p>

<p>Some parts of the expression are factorized and when I expand the expression they get simplified, thus making the substitution impossible. For example</p>

<pre><code>(((x+1)**2-x).expand()).subs(x**2+2*x, y+1)
</code></pre>

<p>will give <code>x^2+x+1</code> and what I am looking for is <code>y+2-x</code>.</p>

<p><strong>Question</strong></p>

<p>Is there a way to solve these problems ? Or maybe I should use another symbolic mathematical tool ? Any suggestions are welcomed.</p>

<p>Here's a possible solution to your problems:</p>

<pre><code>from sympy import *

a = symbols('a')
b = symbols('b')
expr = 1 / 12 * b + 1
print(expr.subs((1 / 12) * b, a))
print(expr.subs(b * (1 / 12), a))

x = symbols('x')
y = symbols('y')
expr = ((x + 1)**2 - x).expand()
print(expr.subs(x**2 + x, y - x + 1))
</code></pre>

python sympy substitution symbolic-math