shuffling elements of a list

Fredrik Lundh fredrik at pythonware.com
Wed May 31 17:05:14 EDT 2006


Roger Miller wrote:

> DSU seems like a lot of trouble to go through in order to use an O(n
> log n) sorting algorithm to do what can be done in O(N) with a few
> lines of code.  The core code of random.shuffle() shows how easy it is
> to do it right:
> 
>         for i in reversed(xrange(1, len(x))):
>             # pick an element in x[:i+1] with which to exchange x[i]
>             j = int(random() * (i+1))
>             x[i], x[j] = x[j], x[i]

easy to do it right?  you know, the main reason for adding shuffle to 
the standard library was that its way too easy to get it wrong.

see e.g. this thread: http://tinyurl.com/ppgzq

</F>




More information about the Python-list mailing list