I'm trying to use the Count function for this purpose, but it's not working how I'd like it to. Does anybody know a simple way to do this counting?

I would like to be counting the number of "p"s in expressions like

p[1,2][1]^2 p[3,4][3]



I would like the count to return 2 on the first one (even though one of the p's has a squared term), and 1 on the second.

edit: I realized for the purpose of counting I can remove the "square" so the first expression would just look like


if that makes it any easier.

  • $\begingroup$ Do they always come in the form p[a, b][t]? $\endgroup$ – march Oct 9 '15 at 19:00
  • $\begingroup$ What should it return of f[p]? $\endgroup$ – Dr. belisarius Oct 9 '15 at 19:00
  • $\begingroup$ @belisariusisforth: Seems like you're violating your Principle of don't-ask-questions-to-expand-the-scope-of-the-question. :) $\endgroup$ – march Oct 9 '15 at 19:02
  • $\begingroup$ @march yes they do. $\endgroup$ – Alex Mathers Oct 9 '15 at 19:07

One way is to turn it into a string and count the number of occurences of p in the string:

StringCount[ToString[p[1, 2][1]^2 p[3, 4][3]], "p"]
  • $\begingroup$ I had just figured this out and was about to answer my own question with that! Thanks though. $\endgroup$ – Alex Mathers Oct 9 '15 at 18:59
  • 1
    $\begingroup$ Ahem: p["p"]... :D (To be fair to you, the OP didn't mention that they only wanted to count symbols although that's how I interpreted the question) $\endgroup$ – rm -rf Oct 10 '15 at 11:22

This works:

Count[p[1, 2][1]^2 p[3, 4][3], _p, ∞, Heads -> True]

"And Now for Something Completely Different"...

expr = p[1, 2][1]^2 p[3, 4][3];

Module[{n = 0}, expr /. p :> n++; n]

(*  2  *)

No claim to be "best"

  • $\begingroup$ Cute, though: +1. $\endgroup$ – march Oct 9 '15 at 20:39
Length[Position[p[1, 2][1]^2 p[3, 4][3], p]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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