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.
Answer
Here's one way to count the number of multiplications in an expression (equal to or greater than the number of Times
in the expression). It should also work for several other binary operators, Listable
or not (although I haven't tested it on them).
t[x_, oper_: Times] := Tr @ ((Length[#] - 1) & /@
(Extract[x, {Sequence @@ Drop[#, -1]}] & /@ Position[x, oper]))
Usage
t[a b c + d e + f[a b] - 1/f[f[c d]]]
6
Under the hood.
Let's examine a b c + d e + f[a b] - 1/f[f[c d]]
, using Position
and Extract
and TreeForm
.
The tree structure of the expression...
ClearAll[a, b, c, d, e, f]
(x = a b c + d e + f[a b] - 1/f[f[c d]]) // TreeForm
Then the positions of the head, Times
.
Position[x, Times]
{{1, 0}, {2, 0}, {3, 1, 0}, {4, 0}, {4, 2, 1, 1, 1, 0}}
By dropping the final zero from each position, we obtain the instances of Times
, including the arguments.
Extract[x, {Sequence @@ Drop[#, -1]}] & /@ %
{a b c, d e, a b, -(1/f[f[c d]]), c d}
...the number of items.
Length[%]
5
[t[]
goes a step further to count the (arguments-1) for each Times
, namely, 6.]
...a look at the structure of each of those instances of Times
.
TreeForm /@ %%
Comments
Post a Comment