MathGroup Archive 2004

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

Search the Archive

Re: List element replacement.

  • To: mathgroup at
  • Subject: [mg52022] Re: [mg51980] List element replacement.
  • From: DrBob <drbob at>
  • Date: Sun, 7 Nov 2004 01:04:06 -0500 (EST)
  • References: <>
  • Reply-to: drbob at
  • Sender: owner-wri-mathgroup at

Does this do the trick? (My testing wasn't extensive.)

removeAndReplace::usage = "
removeAndReplace[a,b,c] checks whether List a is
     contained in List b (counting multiplicities). If no, b is returned. If \
yes, the return value is b with the elements of a removed and the elements of \
c added (counting multiplicities and sorted)."
removeAndReplace[a_List, b_List, c_List] := Block[{aFreq, bFreq, f, pos},
       Length@a > Length@b, b,
       Length@(aFreq = Frequencies@a) > Length@(bFreq = Frequencies@b), b,
       f[{n_, x_}] := ((pos = Position[bFreq[[All, 2]],
       x]) === {} || (n > Extract[bFreq, {pos[[1, 1]], 1}])) && Throw[False];
       Catch[Scan[f, aFreq]; Throw@True],
       f[lst_, {n_, x_}] := DeleteCases[lst, x, {1}, n];
       Sort@Fold[f, Join[b, c], aFreq],
       True, b]

This could be useful without the Sort, so I'd probably omit it and enter Sort@removeAndReplace[a,b,c], if I needed a sorted result.

In that case, when it removes elements, it removes them starting at the front of Join[b,c].


On Sat, 6 Nov 2004 02:07:45 -0500 (EST), Robert G. Wilson v <rgwv at> wrote:

> Et al,
> 	HELP, I tried this once before but what I received back I could not make it work.
> Therefore I am following the adage that if at first you do not succeed then wait
> awhile, rethink, restate and resubmit.
> 	I have three lists of objects, sorted but not unioned, that is there are elements
> which will be repeated. Let us label them 'initial' list, 'compare' list, and
> 'replace' list. If all of the elements in the 'compare' list, including repeats,
> are in the 'initial' list, then remove those elements and put in the elements from
> the 'replace' list.
> Thank you in advance,
> Bob.

DrBob at

  • Prev by Date: Re: dashing the lines make the plot looks so bad
  • Next by Date: Re: Re: Notebook output write to a different file
  • Previous by thread: Re: List element replacement.
  • Next by thread: Re: List element replacement.