4
$\begingroup$

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.

$\endgroup$
4
  • $\begingroup$ Do they always come in the form p[a, b][t]? $\endgroup$
    – march
    Oct 9, 2015 at 19:00
  • $\begingroup$ What should it return of f[p]? $\endgroup$ Oct 9, 2015 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, 2015 at 19:02
  • $\begingroup$ @march yes they do. $\endgroup$ Oct 9, 2015 at 19:07

4 Answers 4

4
$\begingroup$

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"]
$\endgroup$
2
  • $\begingroup$ I had just figured this out and was about to answer my own question with that! Thanks though. $\endgroup$ Oct 9, 2015 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, 2015 at 11:22
12
$\begingroup$

This works:

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

"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"

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

Your Answer

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

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