addition to MLab: randperm

Jim Dennis jimd at vega.starshine.org
Sat Feb 2 17:54:58 EST 2002


In article <a2972632.0201171005.15e660e3 at posting.google.com>, les ander wrote:

> I needed the matlabs randperm function so i wrote one and 
> wanted to see if there is a better way. I think this function would
> be a good addition to MLab:

> # given a number n, return an array that is a shuffling of 
> # integers from range 0 to n 

 I must be missing something in your requirements.
 What's wrong with:

	 def randperm(n):
		import random
		t = range(n)
		random.shuffle(t)
		return t


> def randperm(n):
>  import MLab,Numeric
>  r=MLab.rand(n)
>  dict={}
>  for i in range(n):
>     dict[ r[i] ]=i
>  r=Numeric.sort(r)
>  out=Numeric.zeros(n)
>  for i in range(n):
>     out[i]=dict[r[i]]
>  return out


> i encourage other people to post the code if they write
> more matlab type functions using the Numeric package




More information about the Python-list mailing list