If I want to count the number of times that ^
occurs in an expression x
, that's easy:
Count[x, _Power, {0, Infinity}]
Suppose I want to count only instances of -1 raised to some power. How can I do that?
I had tried
Count[(-1)^n + 2^n, _Power[-1, _], {0, Infinity}]
and even
Count[Plus[Power[-1, n], Power[2, n]], _Power[-1, _], {0, Infinity}]
but both gave 0.
The origin of the question: I'm building a ComplexityFunction
that allows certain expressions like Power[-1, anyComplicatedExpressionHere]
and Sqrt[5]
(relevant to my problem) but heavily penalizes other uses of Power
and Sqrt
.
You would do Count[x,Power[-1,_], {0, Infinity}]
In[4]:= RandomInteger[{-1, 1}, 10]^RandomChoice[{x, y, z}, 10]
Out[4]= {(-1)^x, (-1)^x, 0^y, 0^z, (-1)^z, 1, 1, 1, (-1)^y, 0^x}
In[5]:= Count[%, (-1)^_, {0, Infinity}]
Out[5]= 4
What is about
Count[expr, Power[-1, _], {0, Infinity}]
P.S. Example in the question is not correct. I think you probably mean
Count[x, _Power, {0, Infinity}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With