MathGroup Archive 1998

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

Search the Archive

Re: Q: efficient list operation wanted

  • To: mathgroup at smc.vnet.net
  • Subject: [mg14006] Re: [mg13973] Q: efficient list operation wanted
  • From: BobHanlon at aol.com
  • Date: Sat, 12 Sep 1998 16:59:27 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

The following function handles the case when there are more instances in
the target list of the target value to be replaced than there are
elements in the replacement list (withList). It will "cycle" through
the replacement list as often as necessary to replace all instances of
the target value.

substitute[targetList_List, withList_List, targetValue_] := 
	Module[{n, replacements}, 
		replacements = Nest[Prepend[#, withList]&, 
			withList, Ceiling[Count[targetList, targetValue]/
				Length[withList]]-1]//Flatten;
		n=0; targetList /. targetValue :> 
			(n++; replacements[[n]])]

L1 = {1, 2, 3, 4, 5, 3, 7, 2, 3, 9}; L2 = {a, b, c}; substitute[L1, L2,
3]

{1,2,a,4,5,b,7,2,c,9}

L1 = {1, 2, 3, 4, 5, 3, 7, 2, 3, 9, 3, 10, 3}; substitute[L1, L2, 3]

{1,2,a,4,5,b,7,2,c,9,a,10,b}

L1 = Table[5, {15}]; L2 = {a, b, c, d}; L3 = substitute[L1, L2, 5]
substitute[L3, {1, 5, 9, 13}, a]

{a,b,c,d,a,b,c,d,a,b,c,d,a,b,c}
{1,b,c,d,5,b,c,d,9,b,c,d,13,b,c}

Bob Hanlon
______________

My original response was unnecessarily complex. This simpler form also
works:

n=0; L1 /. 3 :> (n++; L2[[n]])

Bob Hanlon
_______________

L1 = {1, 2, 3, 4, 5, 3, 7, 2, 3, 9}; L2 = {a, b, c};

n=0;
L1 /. (x_/;x==3) :> (n++; L2[[n]])

{1,2,a,4,5,b,7,2,c,9}

Bob Hanlon

In a message dated 9/11/98 7:54:56 PM, k.duellmann at uni-mannheim.deXXX
wrote:

>I am looking for an efficient solution of the following problem:
>
>Given two lists L1 = {1,2,3,4,5,3,7,2,3,9} and L2 = {a, b, c}
>
>I want to replace all numbers 3 in L1 by the elements of L2
>successively,
>that is the first 3 by a, the second 3 by b and the third 3 by c. That
>is I want to get the following modified L1-list: {1,2,a,4,5,b,7,2,c,9}.
>
>Replace[] unfortunately replaces elements with a single element only. Is
>there a chance to avoid hideous Do-Loops?
>
>Any hints are appreciated!


  • Prev by Date: Re: Select x s.t. y>10
  • Next by Date: Re: Select x s.t. y>10
  • Previous by thread: Re: Q: efficient list operation wanted
  • Next by thread: Re: Q: efficient list operation wanted