general expression substitution in sympy

Viewed 1016

I have two univariate functions, f(x) and g(x), and I'd like to substitute g(x) = y to rewrite f(x) as some f2(y).

Here is a simple example that works:

In [240]: x = Symbol('x')

In [241]: y = Symbol('y')

In [242]: f = abs(x)**2 + 6*abs(x) + 5

In [243]: g = abs(x)

In [244]: f.subs({g: y})
Out[244]: y**2 + 6*y + 5

But now, if I try a slightly more complex example, it fails:

In [245]: h = abs(x) + 1

In [246]: f.subs({h: y})
Out[246]: Abs(x)**2 + 6*Abs(x) + 5

Is there a general approach that works for this problem?

1 Answers
Related