I'm trying to count the number of times multiplication appears in an expression (for the purpose of constructing a ComplexityFunction that would help me simplify a terrible algebraic expression for later numerical crunching in matlab).
For example, I consider the following expression to involve 3 multiplications:
a b c + d e
two in "abc" and one in "de".
I've tried Level, but unfortunately mathematica sees the term "abc" as one "Times" with three arguments:
In:= Level[a b c + d e, {-1}, Heads->True]
Out:= {Plus, Times, a, b, c, Times, c, d}
In principle I could reverse-engineer the multiplicity of arguments of "Times" from the above, but that seems like an unnecessarily cumbersome way.
i'd greatly appreciate any help.
Flat
attribute ofTimes
, you'll never seeTimes[a, Times[b, c]]
. There might be dark, back alley routes to spelunk and do some ugly pre-parsing, etc., but I don't think it'd be any less "cumbersome", not to mention the loss in intent and clarity. As an alternative, you could consider converting your expression toInputForm
, then a string and counting the*
s $\endgroup$*
in theInputForm
string is most in line with what i originally hoped to accomplish, thanks! $\endgroup$