【问题标题】:Counting expressions in Mathematica在 Mathematica 中计算表达式
【发布时间】:2011-07-01 17:10:44
【问题描述】:

如果我想计算^ 在表达式x 中出现的次数,这很简单:

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

假设我只想计算 -1 提高到某个幂的实例。我该怎么做?

我试过了

Count[(-1)^n + 2^n, _Power[-1, _], {0, Infinity}]

甚至

Count[Plus[Power[-1, n], Power[2, n]], _Power[-1, _], {0, Infinity}]

但都给了 0。

问题的起源:我正在构建一个ComplexityFunction,它允许某些表达式,如Power[-1, anyComplicatedExpressionHere]Sqrt[5](与我的问题相关),但严重惩罚PowerSqrt 的其他用途。

【问题讨论】:

  • 代码应该是Count[x, _Power, {0, Infinity}]
  • 请注意,Power 并不总是对应于表达式中某处的^,例如1/xFullForm 中是 Power[x,-1]。请注意,有一些这样的怪癖,以防它与您的问题相关。

标签: wolfram-mathematica


【解决方案1】:

你会做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

【讨论】:

  • 有趣。我在发布之前尝试了Count[(-1)^n + 2^n, _Power[-1, _], {0, \[Infinity]}],结果为 0。
  • 这是因为_Power 匹配Power[___],所以您的模式正在寻找Power[___][-1,_],但没有。您的模式将匹配(a^b)[-1,n],它具有完整形式Power[a,b][-1,n]。正确的模式应该是Power[-1,_]
  • 感谢您的解释,这对您有帮助。
【解决方案2】:

关于什么

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

附:问题中的示例不正确。我想你可能是说

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

【讨论】:

    【解决方案3】:

    大概

    Count[x, Power[-1, _], Infinity]
    
    • Infinity 的级别规范包括所有级别 1 到无穷大
    • 当基数为-1 时,模式Power[-1, _] 只会匹配Power 的实例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多