sympy substitution of occurences satisfying a given pattern

54 Views Asked by At

Is there a way to do a substitution in sympy of all occurences that satisfy a given pattern? For example, if I have an expression that contains multiple occurances of sqrt(anything), is there a way to substitute all those occurences with anything**0.51?

Here is a code example:

import sympy
from sympy import sqrt, exp
from sympy import *
x,y = symbols('x y') 
test = sqrt (x+y) +  sqrt (exp(y)) 

in this case I can do substitution manually:

test.subs(sqrt(x+y), (x + y)**0.51).subs(sqrt (exp(y)) , (exp(y))**0.51)

yielding the expected subsitution. But, is there a way to do it one shot so one can easily apply it to long epxressions?

2

There are 2 best solutions below

1
Oscar Benjamin On BEST ANSWER

You can use a Wild symbol to do pattern-matched replacements:

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

In [8]: test
Out[8]: 
               ____
  _______     ╱  y 
╲╱ x + y  + ╲╱  ℯ  

In [9]: test.replace(sqrt(w), w**0.51)
Out[9]: 
                  0.51
       0.51   ⎛ y⎞    
(x + y)     + ⎝ℯ ⎠ 
0
Davide_sd On

You can use the replace method. Here is the documentation with a few examples.

In your particular case, the square root is a power with exponent 0.5, so we are going to look for those objects:

test.replace(lambda t: t.is_Pow and t.exp is S.Half, lambda t: t.base**0.51)