Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple power counting

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.

like image 927
sjdh Avatar asked May 04 '26 07:05

sjdh


1 Answers

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}
like image 76
Simon Avatar answered May 06 '26 02:05

Simon