Replace first occurrence in expression

48 views
Skip to first unread message

Thomas Ligon

unread,
Aug 1, 2024, 1:49:20 PM8/1/24
to sympy

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

Aaron Meurer

unread,
Aug 1, 2024, 3:52:50 PM8/1/24
to sy...@googlegroups.com
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
> --
> 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+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/febcad9b-c406-4636-965f-ab9afec8f501n%40googlegroups.com.

Thomas Ligon

unread,
Aug 2, 2024, 3:48:11 PM8/2/24
to sympy
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.

Chris Smith

unread,
Aug 13, 2024, 10:41:52 AM8/13/24
to sympy
Though you solved your issue, you might also want to be aware of the tools in core/traversal --  ne of the preorder_traversal or postorder_traversal tools allows you to exit after the first occurrance  --  and simplify/epath.

/c

Reply all
Reply to author
Forward
0 new messages