开发者

Counting expressions in Mathematica

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开发者_如何学Python 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}]


Probably

Count[x, Power[-1, _], Infinity]
  • the level specification of Infinity includes all levels 1 through infinity
  • pattern Power[-1, _] will only match the the instances of Power when the radix is -1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜