On 06/01/2022 16:41, Oscar Benjamin wrote:
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
Thanks very much for that Oscar, your solution looks extremely useful
and general. Somehow I hadn't realised the power of Wild(), although I
knew Wild existed. The Wild/replace method looks most useful to me - I
get easily lost in multiple lambda's!.
David
--
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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/82e8af14-7131-4ff2-c804-4eae83818c04%40dbailey.co.uk.