Thanks, that is useful information. After some more work, I can see that the first occurrence, in this case, has other things that distinguish is from the rest, and it turned out to be easy to filter for that, so my original problem is solved.
On Thursday, August 1, 2024 at 9:52:50 PM UTC+2 [email protected] wrote: > As far as I know, this functionality isn't implemented anywhere. The > notion of "first one" would be a little ambiguous anyways because it > would depend on the args ordering, which might not be the same as the > printer order. > > If you are targeting a specific expression and you know of a larger > expression that you want to be treated differently, you could replace > that exact expression. For example, if you had > > expr = sin(a) + cos(a) > > and you wanted to replace a in sin(a) but not in cos(a) you could just > use expr.subs(sin(a), sin(x)). > > Barring that, you would need to write this substitution algorithm from > scratch by walking the expression tree. > > I guess a max_replacements keyword argument could be added to subs or > replace, although this is the first time I've heard of someone needing > it. > > Aaron Meurer > > On Thu, Aug 1, 2024 at 11:49 AM Thomas Ligon <[email protected]> wrote: > > > > I want to remove all occurrences of “a” in expression “exp” except for > the first one, which I want to keep. > > > > To do that, I have tried > > X = symbols(‘X’) > > > > <<replace first occurrence of a by X>> > > > > replace all remaining occurrences by 0 > > > > replace X by a > > > > For the second statement, an Internet search suggested replace, like > this: > > > > X = symbols(‘X’) > > > > exp = exp.replace(a, X, 1) # maximum of one replacement > > > > exp = exp.subs(a, 0) > > > > exp = exp.subs(X, a) > > > > Unfortunately, this version of replace doesn’t work, and I have not > found any way to do it with subs of xreplace. This post tells me that subs > and replace have kwargs, but I haven’t found any documentation on that. > > > > > https://stackoverflow.com/questions/56584025/sympy-subs-vs-replace-vs-xreplace > > > > -- > > 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/febcad9b-c406-4636-965f-ab9afec8f501n%40googlegroups.com > . > -- 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/06887db8-6712-4f1d-b942-142d2cc5403dn%40googlegroups.com.
