Calculating expressions in Mathematica

If I want to count the number of times ^ that occurs in the expression x , this is easy:

 Count[x, _Power, {0, Infinity}] 

Suppose I want to count only -1 instances raised to some extent. How can i do this?

I 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.

Origin of the question: I create a ComplexityFunction that allows certain expressions like Power[-1, anyComplicatedExpressionHere] and Sqrt[5] (related to my problem), but severely punishes other uses of Power and Sqrt .

+4
source share
3 answers

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 
+6
source

What

 Count[expr, Power[-1, _], {0, Infinity}] 

PS The example in the question is incorrect. I think you probably mean

 Count[x, _Power, {0, Infinity}] 
+4
source

maybe

 Count[x, Power[-1, _], Infinity] 
  • Infinity level specification includes all levels from 1 to infinity
  • pattern Power[-1, _] will only match Power instances when radius -1
+3
source

All Articles