random.shuffle?

Erik Max Francis max at alcyone.com
Mon Jul 31 14:37:19 EDT 2000


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.

Better would be this:

    def shuffle(list):
        count = len(list)
        for i in range(count):
            j = whrandom.randint(count)
            list[i], list[j] = list[j], list[i]

Simpler, too.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Love is the most subtle form of self-interest.
\__/ Holbrook Jackson
    Fat Boy and Little Man / http://www.fatboyandlittleman.com/
 Watch Fat Boy and Little Man go about their antics.



More information about the Python-list mailing list