Best way to count this?

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]


or

p[3,3][1]


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

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


if that makes it any easier.

• Do they always come in the form p[a, b][t]? – march Oct 9 '15 at 19:00
• What should it return of f[p]? – Dr. belisarius Oct 9 '15 at 19:00
• @belisariusisforth: Seems like you're violating your Principle of don't-ask-questions-to-expand-the-scope-of-the-question. :) – march Oct 9 '15 at 19:02
• @march yes they do. – 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"]

• I had just figured this out and was about to answer my own question with that! Thanks though. – Alex Mathers Oct 9 '15 at 18:59
• 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) – 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"

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