Re: Pattern matching problem

*To*: mathgroup at smc.vnet.net*Subject*: [mg88565] Re: Pattern matching problem*From*: Szabolcs Horvát <szhorvat at gmail.com>*Date*: Thu, 8 May 2008 04:16:15 -0400 (EDT)*Organization*: University of Bergen*References*: <fvs2kf$eo4$1@smc.vnet.net>

Charlie Brummitt wrote: > Hi all, > Here is my problem: Given a polynomial in the variables u[x,t] and its > spatial derivatives (for example, the polynomial could be 1 + u + > u_xx*u_xxx^2), count the number of spatial derivatives with multiplicity. > That is, after writing the above polynomial as > > > 1 + u + u_xx * u_xxx * u_xxx > > the output should be 2 + 3 + 3 (basically, you count the number of x's). > > I have tried implementing this using a pattern matching approach. Here is > what I tried: > > f[equation_ ] := Sum[ k * j * Count[ equation , D[ u[x, t], {x, j} ] ^ k , > {0, \infinity} ], {j, 1, 50}, {k, 1, 50}] > > This fails to work on, for example, the input u_xx^2, because it outputs 6 > when it should output 4. This is because the u_xx is counted (+2 to the > sum), and the u_xx^2 is counted (+4 to the sum). This is because the u_xx is > nested inside the Power[ , 2] in its representation in Mathematica and so > it gets counted too many times in my formula. I can't seem to figure out a > way to use the "provided that" operator /; to make this formula work. > > I've also tried doing some replacement methods, but to no success. > > Thanks for any help you may be able to provide. > One possibility is replacing the Power[] with an explicit product: In[1]:= ee=1+u[x,t]+D[u[x,t],{x,2}] D[u[x,t],{x,3}]^2 Out[1]= 1+u[x,t]+(u^(2,0))[x,t] (u^(3,0))[x,t]^2 In[2]:= ee1 = ee /. expr_^n_Integer /; n>1 :> (HoldForm@Times[##]&) @@ ConstantArray[expr,n] Out[2]= 1+u[x,t]+((u^(3,0))[x,t] (u^(3,0))[x,t]) (u^(2,0))[x,t] In[3]:= Cases[ee1, HoldPattern[Derivative[n_,_][u][__]] :> n, Infinity] Out[3]= {3,3,2} In[4]:= Plus@@% Out[4]= 8 Just a consistency check: In[5]:= ReleaseHold[ee1] == ee Out[5]= True