Skip to main content
make code more efficient by searching only for the first occurrence rather than all
Source Link
Mr.Wizard
  • 273.1k
  • 34
  • 595
  • 1.4k

Well here's a way. First collectFind the positionsposition of allthe first occurrence of x:

posexpr = Position[HoldForm[xHoldForm[x + 2 + 4 + x]x];

pos = Position[expr, x];x, -1, 1];

Then:

ReplacePart[HoldForm[x + 2 + 4 + x]ReplacePart[expr, First[pos]pos -> 4]

4 + 2 + 4 + x

Well here's a way. First collect the positions of all x:

pos = Position[HoldForm[x + 2 + 4 + x], x];

Then:

ReplacePart[HoldForm[x + 2 + 4 + x], First[pos] -> 4]

4 + 2 + 4 + x

Well here's a way. Find the position of the first occurrence of x:

expr = HoldForm[x + 2 + 4 + x];

pos = Position[expr, x, -1, 1];

Then:

ReplacePart[expr, pos -> 4]

4 + 2 + 4 + x

Source Link
RunnyKine
  • 33.3k
  • 3
  • 110
  • 176

Well here's a way. First collect the positions of all x:

pos = Position[HoldForm[x + 2 + 4 + x], x];

Then:

ReplacePart[HoldForm[x + 2 + 4 + x], First[pos] -> 4]

4 + 2 + 4 + x