# How can I delete a random part of an expression?

I have the expression:

Times[0.19157500241430547,Power[Plus[0.7235014213631388,k,Times[-1,Power[m,c]]],Times[g,z]]]

Also represented as:

0.191575 (0.723501 + k - m^c)^(g z)


I want to randomly select either a symbol or real and delete it from the expression, so the expression might become:

0.191575 (k - m^c)^(g z)


Or maybe:

0.191575 (0.723501 + k - m^c)^(z)


Is there a simple way to do this?

• If there were even a way to use Dimensions[] to get all of the dimensions of the expression, I could use those dimensions to plug in for Delete[]. Sep 10, 2018 at 19:13

## 3 Answers

Clear@expr
expr=0.191575 (0.723501 + k - m^c)^(g z)
Delete[expr,RandomChoice@Position[expr, x_ /; Length@x == 0, Heads -> False]]

(*Original: 0.191575 (0.723501 +k-m^c)^(g z)
New: (0.723501 +k-m^c)^(g z)*)

• I would use Position[expr, _Symbol | _Real, {-1}, Heads -> False] instead. Sep 10, 2018 at 19:42
• It works, thanks!! Sep 10, 2018 at 19:44

Maybe, as a simple but general utility function, you can use this:

RandomDelete[expr_, pattern_, opts___] := Delete[
expr,
RandomChoice[Position[expr, pattern, opts]]
]


Then you can use it to randomly delete symbols:

RandomDelete[0.191575 (0.723501 + k - m^c)^(g z), _Symbol]


Or reals:

RandomDelete[0.191575 (0.723501 + k - m^c)^(g z), _Real]


And use the Heads option that is used by Position:

Table[RandomDelete[f[x, y], _, Heads -> False], 30]


I've added this to my Prototypes paclet, available here:

PacletInstall["https://github.com/arnoudbuzing/prototypes/releases/download/v0.4.1/Prototypes-0.4.1.paclet"]


(And to uninstall, run PacletUninstall["Prototypes"])

Its documentation page has a few examples on how you can use it:

• Awesome, thanks! Sep 11, 2018 at 17:36
deleteRandomCase = DeleteCases[#, RandomChoice[Cases[#, _Symbol | _Real, -1]], -1, 1] &;


Examples:

Table[deleteRandomCase[expr], {5}] // Column // TeXForm


$\begin{array}{l} 0.191575 \left(0.723501\, -m^c\right)^{g z} \\ 0.191575 \left(-m^c+k+0.723501\right)^g \\ \left(-m^c+k+0.723501\right)^{g z} \\ 0.191575 \left(k-m^c\right)^{g z} \\ 0.191575 \left(k-m^c\right)^{g z} \\ \end{array}$