MathGroup Archive 2006

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

Search the Archive

RE: Replacing Numbers in a List

  • To: mathgroup at smc.vnet.net
  • Subject: [mg68276] RE: [mg68230] Replacing Numbers in a List
  • From: "David Annetts" <davidannetts at aapt.net.au>
  • Date: Mon, 31 Jul 2006 03:45:43 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

Hi Gregory,

> Hello everyone,
> I have a long list of integers called x, and I want to 
> replace those that are members of list y with the number 222.
> 
> I did it this way with a Do loop.
> 
> y = {122, 211, 212, 221, 223, 232, 322}; Do[x = 
> ReplacePart[x,222, Position[x, y[[i]]]],{i, Length@y} ]
> 
> Is this OK, or is there a more direct way?

It's OK if it works ....  Or if it's quicker ....  Or both ....

Perhaps another method might be to avoid the Do[] loop.  For some test data

	x = Random[Integer, {0, 20}] & /@ Range[128];
	y = Random[Integer, {0, 20}] & /@ Range[16];

Code that avoids a loop might be

	Timing[
  		rpl = Partition[Flatten[Position[x, #] & /@ y], 1];
  		za = ReplacePart[x, 222, rpl];
  		]

Whereas you have

	Timing[
		Do[
			x = ReplacePart[x, 222, Position[x, y[[i]]]], 
			{i, Length@y} 
			]
  		]

You can compare the two lists using 

	SameQ[za, x]

On my machine (3 GHz running XP), loops appear quicker when x has fewer than
2^15 elements.

Regards,

Dave.


  • Prev by Date: Re: Replacing Numbers in a List
  • Next by Date: Re: Replacing Numbers in a List
  • Previous by thread: Re: Replacing Numbers in a List
  • Next by thread: Re: Replacing Numbers in a List