random.shuffle?

François Pinard pinard at iro.umontreal.ca
Mon Jul 31 16:06:54 EDT 2000


[Erik Max Francis]

> François Pinard wrote:

> > def shuffle(items):
> >     """Shuffle ITEMS in place.  ITEMS should normally be a list."""
> >     for top in range(len(items)-1, 0, -1):
> >         index = whrandom.randint(0, top)
> >         items[index], items[top] = items[top], items[index]

> This is a biased shuffling algorithm.  When swapping cards, you'd want
> to pick the other card from the whole of the deck, not the deck that
> you've touched so far.  If you start with a sorted deck, for instance,
> it's easy to see that cards can't end up in every place; see Knuth.

"See Knuth" is rather vague.  It reads like "Go fishing!".  It would be
more polite giving some precise reference of what you want me to look at.
You also write: "It's easy to see that cards can't end up in every place;".
I may be stubborn and opaque, but I do not see it.  Please kindly explain.

My feeling is that the algorithm above corresponds to what is being written
in the Art of Computer Programming, volume II, section 3.4.2, algorithm P.
My transcription may be wrong, of course, but then, please tell me where.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list