Accepting that in Mathematica -c/y
is automatically converted to -1*c*y^-1
and permitting the result shown in Andy's answer I believe we can use a simpler approach, at least for the kind of expression given in example.
Define rules
that determine how a Times
or Power
expression should be counted, then usesuse Cases
to find all instances in you expression and total them with Tr
:
rules = {
_*x__ :> Length@{x},
_^n_?Positive :> n - 1
};
expr = a + s^2*b - c/y + o^3 + n*m*u;
Tr @ Cases[expr, #, -2] & /@ rules
Tr @ %
{5, 3}
8
As a single function:
fn[expr_] :=
Tr @ Cases[expr, #, -2] & /@ {_*x__ :> Length@{x}, _^n_?Positive :> n - 1} // Tr
String conversion
If you prefer a string processing result, now accepting that the form Mathematica uses may seem rather arbitrary, I propose:
stringfn[expr_] :=
StringCases[
ToString[expr, InputForm],
{"*" :> 1, "^" ~~ d__?DigitQ :> FromDigits[d] - 1}
] // Tr
a + s^2*b - c/y + o^3 + n*m*u // stringfn
6