简单的功率计数

发布于 2024-12-22 00:46:30 字数 233 浏览 3 评论 0原文

如何在如下表达式中添加 x 的幂数?

x^2f[x]g[x^3]

or

x^2g[x^4]

or

x^2g[x^2f[x^2]]

计数使得所有这些示例都必须返回 6。 我正在考虑将 Count 与某种模式一起使用,但我没有设法为此构建一个模式。

How can one add the number of powers of x in expressions like the following?

x^2f[x]g[x^3]

or

x^2g[x^4]

or

x^2g[x^2f[x^2]]

The counting is such that all these examples must return 6.
I was thinking of using Count with some pattern, but I didn't manage to construct a pattern for this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野却迷人 2024-12-29 00:46:30

这是我的快速技巧 - 某些行为(请参阅最后一个示例)可能不完全是您想要的:

SetAttributes[countPowers, Listable]
countPowers[expr_, symb_] := Module[{a}, 
  Cases[{expr} /. symb -> symb^a // PowerExpand, symb^n_ :> n, 
        Infinity] /. a -> 1 // Total]

然后

In[3]:= countPowers[{x^2 f[x] g[x^3], x^2 g[x^4], x^2 g[x^2 f[x^2]]}, x]

Out[3]= {6, 6, 6}

In[4]:= countPowers[{x^(2 I)  g[x^3], g[x, x^4], 
                       x^2 g[E^(2 Pi I x) , f[x]^x]}, x]

Out[4]= {3 + 2 I, 5, 5}

Here's my quick hack - some of the behaviour (see the final example) might not be quite what you want:

SetAttributes[countPowers, Listable]
countPowers[expr_, symb_] := Module[{a}, 
  Cases[{expr} /. symb -> symb^a // PowerExpand, symb^n_ :> n, 
        Infinity] /. a -> 1 // Total]

Then

In[3]:= countPowers[{x^2 f[x] g[x^3], x^2 g[x^4], x^2 g[x^2 f[x^2]]}, x]

Out[3]= {6, 6, 6}

and

In[4]:= countPowers[{x^(2 I)  g[x^3], g[x, x^4], 
                       x^2 g[E^(2 Pi I x) , f[x]^x]}, x]

Out[4]= {3 + 2 I, 5, 5}
嗼ふ静 2024-12-29 00:46:30

由于您想将 x 算作 1 的隐式幂,因此可以使用以下形式:

powerCount[x_Symbol][expr_] := 
  Tr @ Reap[PowerExpand[expr] /. {x^n_ :> Sow[n], x :> Sow[1]}][[2,1]]

powerCount[x] /@
  {
   x^2f[x]g[x^3],
   x^2g[x^4],
   x^2g[x^2f[x^2]]
  }
{6, 6, 6}

或者,如果这样更易于阅读,也可以不使用 Sow 和 Reap 来编写:

powerCount[x_Symbol][expr_] := 
  Module[{t = 0}, PowerExpand[expr] /. {x^n_ :> (t += n), x :> t++}; t]

任一形式都可以变得更简洁使用消失的模式,但可能会牺牲清晰度:

powerCount[x_Symbol][expr_] := 
  Tr @ Reap[PowerExpand[expr] /. x^n_ | x :> Sow[1 n]][[2, 1]]

Since you want to count x as an implicit power of 1, you could use this:

powerCount[x_Symbol][expr_] := 
  Tr @ Reap[PowerExpand[expr] /. {x^n_ :> Sow[n], x :> Sow[1]}][[2,1]]

powerCount[x] /@
  {
   x^2f[x]g[x^3],
   x^2g[x^4],
   x^2g[x^2f[x^2]]
  }
{6, 6, 6}

Alternatively, this could be written without Sow and Reap if that makes it easier to read:

powerCount[x_Symbol][expr_] := 
  Module[{t = 0}, PowerExpand[expr] /. {x^n_ :> (t += n), x :> t++}; t]

Either form can be made more terse using vanishing patterns, at the possible expense of clarity:

powerCount[x_Symbol][expr_] := 
  Tr @ Reap[PowerExpand[expr] /. x^n_ | x :> Sow[1 n]][[2, 1]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文