Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Function to detect presence of a variable in

  • To: mathgroup at smc.vnet.net
  • Subject: [mg109411] Re: Function to detect presence of a variable in
  • From: Bob Hanlon <hanlonr at cox.net>
  • Date: Sun, 25 Apr 2010 06:26:53 -0400 (EDT)

Count[(1/x)^x, x, -1]

2

Count[(2/x)^(x*w^4*z), x, -1]

3

This gives an enexpected result because Count is operating on the FullForm in which x appears 3 times

(2/x)^(x*w^4*z) // FullForm

Times[Power[2,Times[Power[w,4],x,z]],Power[Power[x,-1],Times[Power[w,4],x,z]]]

You can freeze the form with Unevaluated

Count[Unevaluated[(2/x)^(x*w^4*z)], x, -1]

2

ClearAll[countMeIn];

SetAttributes[countMeIn,
  {HoldFirst, Listable}];

countMeIn[expr_, var_] :=
 Count[Unevaluated[expr],
  var, -1]

countMeIn[(2/x)^(x*w^4*z), x]

2

countMeIn[(2/x)^(x*w^4*z), {x, y, w, z}]

{2,0,1,1}


Bob Hanlon

---- carlos at colorado.edu wrote: 

=============
I would like to have a function

            k = CountMeIn[expr,var]

that returns the number of times var appears in expr, eg.
CountMeIn[(1/x)^x,x]  returns 2. var could be a list, in which case
k would be a conforming list: k = CountMeIn[(2/x)^(x*w^4*z),{x,y,w,z}]
should return {2,0,1,1}.  expr is never a list.

Tried to use Position for this, but the behavior is finicky:
Position[1/x,x] returns {{1,1}} but Position[x,x] or Position[1*x,x]
returns {{}}  (why?)  May be expr should be converted  to {expr}
inside the function for safety?



  • Prev by Date: Re: problems with NMinimize
  • Next by Date: Re: Stop mathematica reordering expression during matrix multiply
  • Previous by thread: How to make GraphicsGrid use different cell sizes?
  • Next by thread: Re: Function to detect presence of a variable in