MathGroup Archive 2008

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

Search the Archive

Re: Select from list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg87762] Re: Select from list
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Wed, 16 Apr 2008 07:14:23 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <fu4fjb$nhp$1@smc.vnet.net>

Steve Gray wrote:
> I have a list like this:
> 
> ptX=
> {{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}}
> 
> and I want a list pointing to all the sublists above that contain both
> a 2 and a 3. In this example I would get {1,2,5}. The best solution I
> have, with more generality, is:
> 
> va = 2;
> vb = 3;
> za = Map[Cases[#1, va]&, ptX] /. {} -> {0}
> zb = Map[Cases[#1, vb]&, ptX] /. {} -> {0}
> Flatten[Position[za*zb, {va*vb}]]
> 
> which gives
> 
> {{2}, {2}, {2}, {0}, {2}}
> {{3}, {3}, {0}, {3}, {3}}
> {1, 2, 5}. 
> 
> (This doesn't work if va or vb is zero. That's ok.)
> There's probably a better way. Anyone? Thank you.

Hi Steve,

The following solution uses directly Position[] and works with zeros.

     Position[ptX, x_ /; MemberQ[x, 2] && MemberQ[x, 3]] // Flatten

For instance,

In[1]:= ptX = {{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4,
     5}, {2, 3, 4, 5}};
Position[ptX, x_ /; MemberQ[x, 2] && MemberQ[x, 3]] // Flatten

Out[2]= {1, 2, 5}

In[3]:= ptX = {{1, 2, 3, 4, 0}, {1, 2, 3, 5}, {1, 2, 4, 5, 0}, {1, 3,
     4, 5},
        {0, 2, 3, 4, 5}};
Flatten[Position[ptX, x_ /; MemberQ[x, 0] && MemberQ[x, 3]]]

Out[4]= {1, 5}

Regards,
-- Jean-Marc


  • Prev by Date: Re: Help with minimization of Eigenvalues
  • Next by Date: Re: Extending Integrate[]
  • Previous by thread: Re: Select from list
  • Next by thread: Re: Select from list