MathGroup Archive 2008

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

Search the Archive

Re: List complement operator

  • To: mathgroup at smc.vnet.net
  • Subject: [mg85025] Re: [mg84950] List complement operator
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Thu, 24 Jan 2008 04:45:39 -0500 (EST)
  • References: <200801210906.EAA09417@smc.vnet.net>

On Jan 21, 2008, at 4:06 AM, zac wrote:

> Dear group,
>
> I'm loooking for an elegant and efficient way to subtract a list (not
> a set) from an other one.
>
> a = {1, 1, 1, 2, 3, 3, 4, 5, 5, 5, 2, 6, 7, 7};
> b = {1, 2, 2, 3, 4, 7, 8};
>
> Complement[a,b] returns {5, 6}, as expected. However I would like to
> treat each entry as a discrete element, therefore my target result is:
> {1, 1, 3, 5, 5, 5, 6, 7}. Union can not be used, although Sort  is
> allowed (ie. whether the result is sorted or not is of no concern).
> Any idea?

It seems you'd like to remove one copy of each element from A that is  
in B, remove that element from B and repeat the process which looks  
like a Fold operation to me.  First define a function that searches  
for an element in a list and remove one copy if found.

removeElement[a_,b_]:=Module[{pos=Position[a,b]},If[pos!={},pos=First 
[Flatten[pos]];Join[a[[;;pos-1]],a[[pos+1;;]]],a]]

then use it in fold to remove a list of elements:

Fold[removeElement[#1,#2]&,a,b]

Regards,

Ssezi


  • Prev by Date: Import , MatrixPlot
  • Next by Date: ColorFunction question - DensityPlot and ContourPlot difference
  • Previous by thread: List complement operator
  • Next by thread: Re: List complement operator