Re: Function to detect presence of a variable in
- To: mathgroup at smc.vnet.net
- Subject: [mg109415] Re: Function to detect presence of a variable in
- From: Raffy <adraffy at gmail.com>
- Date: Mon, 26 Apr 2010 04:50:50 -0400 (EDT)
- References: <hr1584$a82$1@smc.vnet.net>
On Apr 25, 3:24 am, Leonid Shifrin <lsh... at gmail.com> wrote: > Hi Carlos, > > Here is one possibility: > > ClearAll[countMeIn]; > SetAttributes[countMeIn, HoldFirst]; > countMeIn[expr_, var_Symbol] := > Count[Unevaluated[expr], var, Infinity]; > countMeIn[expr_, vars : {__Symbol}] := > Map[countMeIn[expr, #] &, vars]; > > Seems to work as you wanted: > > In[27]:= countMeIn[(2/x)^(x*w^4*z), {x, y, w, z}] > > Out[27]= {2, 0, 1, 1} > > In[28]:= countMeIn[(1/x)^x, x] > > Out[28]= 2 > > One complication which forced me to make it HoldFirst and > use Unevaluated is that expressions that you enter sometimes auto-evaluate > to something else. For example, entering (2/x)^(x*w^4*z) will result in > > In[17]:= (2/x)^(x*w^4*z) > > Out[17]= 2^(w^4 x z) (1/x)^(w^4 x z) > > which has different counts for the variables but is otherwise equivalent to > the original expression. With HoldFirst, the function will analyze your > original expression. > > Hope this helps. > > Regards, > Leonid > > > > On Sat, Apr 24, 2010 at 1:01 AM, <car... 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? Position produces results valid for Extract: Extract[anything, {{}}] === anything, since: Part[anything] === anything