On Sat, 19 Sep 2020 at 23:35, David Bailey <[email protected]> wrote:
>
> On 19/09/2020 20:50, Davide Sandona' wrote:
>
> Hello David,
> in Sympy there are three substitution methods:
> 1. subs: it is the most generic.
> 2. xreplace: it only replace the exact expression you provide.
> 3. replace: this is the most powerful, as it allows for "pattern matching
> operations".
>
> In your case, I would do something like this:
>
> f, g = symbols("f, g", cls=Function)
> a, b, c = symbols("a:c")
> expr = f(a + 2 * b + c)
> expr.replace(f, g)
>
> Thanks for that quick response! Unfortunately I don't think your solution
> really generalises. I mean suppose I wanted to replace
>
> f(anything) by g(5*anything**2)
Hi David,
You can do this using replace but instead of replacing f with g you
can ask to replace all instances of f with a function that will
process the argument(s) that f had. It is convenient to do this in
Python using a lambda function:
In [7]: f = Function('f')
In [8]: g = Function('g')
In [9]: expr = f(1 + sqrt(2))
In [10]: expr.replace(f, lambda arg: g(5*arg**2))
Out[10]:
⎛ 2⎞
g⎝5⋅(1 + √2) ⎠
I'm not sure how well that displays in the email. It looks pretty
screwy in gmail as I write it but I think it does what you want!
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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/CAHVvXxS9BnjYXFq4nnH1qWMe5ZQS0OAbrq6hEEvFwY404v5pCA%40mail.gmail.com.