On Thu, 6 Jan 2022 at 14:41, David Bailey <d...@dbailey.co.uk> wrote:
>
> Dear group,
>
> A substitution like this is easy to make with SymPy:
>
> (a*x**2+b*x+c).subs(x,y)
>
> However, how can I make a conditional substitution, such as:
>
> a) One that would replace even powers of x only.
>
> b) One which would replace even powers of x by y**(n/2) resulting in
> a*y**7+b*x+c? I.e. one where parts of the object being replaced would be
> available to form part of the result - thus x**14 would contribute '7'
> to the resultant expression.

You can use replace to make arbitrary conditions on substitution.
There are different syntaxes so here's how you do it using wild
pattern-matching:

In [15]: expr = (a*x**14 + b*x + c)

In [16]: expr
Out[16]:
   14
a⋅x   + b⋅x + c

In [17]: w = Wild('w')

In [18]: expr.replace(x**w, lambda w: y**(w/2) if w.is_even else x**w)
Out[18]:
   7
a⋅y  + b⋅x + c

Here's how you do it with just functions:

In [19]: query = lambda e: e.is_Pow and e.base == x and e.exp.is_even

In [20]: replacer = lambda e: y**(e.exp/2)

In [21]: expr.replace(query, replacer)
Out[21]:
   7
a⋅y  + b⋅x + c

Since query and replacer can be completely arbitrary functions any
kind of replacement rule can be implemented in this way.

--
Oscar

-- 
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sympy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sympy/CAHVvXxTz4FdkMPYqWH631zVjPjMLqa3Wy57TF87b510%3DztxtLA%40mail.gmail.com.

Reply via email to