# Number of different terms inside mathematical expression

I have expressions of the form $OpA[x\_,y\_]$ and $OpB[x\_,y\_]$ ocurring inside mathematical expressions. I want to create a function which does the following:

CountOperations[expr_]:={number of different expressions of the form OpA[x_,y_] inside expr, number of... OpB[x_,y_] inside expr]}


For example, it should do the following:

In: test=OpA[x,y];
In: CountOperations[test]
Out: {1,0}
In: test=(OpA[1,2]*OpA[2,3]+OpA[1,2]OpB[x,a])/OpB[1,2];
In: CountOperations[test]
Out: {2,2}


because the different expressions are $OpA[1,2]$, $OpA[2,3]$, $OpB[x,a]$ and $OpB[1,2]$. The second $OpA[1,2]$ shall be neglected as it is a duplicate.

So far I have been trying to replace all $Plus$, $Times$ and $Power$ functions with $List$, flatten the list and delete the duplicates, but there must be a better way.

I would be happy if you could help me.

Edit: I wrote polynomials, but I mean general expressions with denominators. Actually, a function for polynomials would be sufficient, but I want to keep everything consistent.

• test does not seem to be a polynomial to me, since you divide by OpB[1,2]. Is integer powers of the Op general enough? Apr 8, 2017 at 16:56
• Oh, you're right... I messed up the definition... I meant general expressions involving those functions. I will have this fixed.
– Fred
Apr 8, 2017 at 16:59
• Length@Variables@test might do it. It depends on the range of use-cases. Apr 8, 2017 at 22:46

## 1 Answer

countOperations[expr_] :=
(Length@DeleteDuplicates@Cases[expr, #, Infinity]) & /@ {OpA[___], OpB[___]}


should do the trick. Cases lists all occurences at any level (down to level Infinity in the expression tree), and then we discard duplicates and take the Length.

• Thank you very much! This appears like the function I have been looking for. I will give it a try and, if it indeed works, vote this as the answer to my question.
– Fred
Apr 8, 2017 at 17:30
• I suggest you let it sit for a day or two before accepting, as there might be better answers out there, waiting to be written :) Apr 8, 2017 at 17:31
• Thanks for that tip, too. But what I can already tell is that it's working perfectly well so far.
– Fred
Apr 8, 2017 at 17:35