1
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ 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? $\endgroup$ Apr 8, 2017 at 16:56
  • $\begingroup$ Oh, you're right... I messed up the definition... I meant general expressions involving those functions. I will have this fixed. $\endgroup$
    – Fred
    Apr 8, 2017 at 16:59
  • $\begingroup$ Length@Variables@test might do it. It depends on the range of use-cases. $\endgroup$
    – Michael E2
    Apr 8, 2017 at 22:46

1 Answer 1

0
$\begingroup$
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.

$\endgroup$
3
  • $\begingroup$ 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. $\endgroup$
    – Fred
    Apr 8, 2017 at 17:30
  • $\begingroup$ 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 :) $\endgroup$ Apr 8, 2017 at 17:31
  • 1
    $\begingroup$ Thanks for that tip, too. But what I can already tell is that it's working perfectly well so far. $\endgroup$
    – Fred
    Apr 8, 2017 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.