Sympy: Replacement using Wild symbols

Viewed 893

I am trying to do generic subexpression replacement.

I want to replace any expression exactly of the form x*y to c.

Note that x and y can be any symbol in the expression.

In the code below, I am using Wild to achieve this, but apparently I am unable to have Wild match symbols only, instead of subexpressions - even with using isinstance=[sp.Symbol].

import sympy as sp
a, b, c = sp.symbols('a b c')

f= a*b - b

x = sp.Wild('x', isinstance=[sp.Symbol])
y = sp.Wild('y', isinstance=[sp.Symbol])

expr = f.replace(x*y, c)

This leads to the following result,

print expr
c

The expected answer though is: c - b

Help is much appreciated!

Thanks!

2 Answers
Related