Is there such a beast as a "perfect" shuffle? :)

Tim Peters tim.one at comcast.net
Fri May 10 17:23:35 EDT 2002


[Christos Georgiou]
>  ...
> Apart from that, which is just a naive approach, any hints / clues for
> building good, uniform random numbers in the range 52! ?

[Tim]
> This is difficult.  Here's one way:
>
> http://www.faqts.com/knowledge_base/view.phtml/aid/4406/fid/546

[Christopher Browne]
> The basic principle is to make sure that you run through them all and
> give opportunity for them to get swapped into any position.
>
> The unbiased way is not quite intuitive...
>
> - You run through from position 1 to position 52
>
> - For each position, select a random location from [present] to
>   the end of the list.
>
> - Swap what's in the current location with the contents of that other
>   random location.

If that's all there were to it, Christos could just call random.shuffle().
However, the *real* problem here is so frequently missed that
random.shuffle's docstring points it out:

>>> import random
>>> print random.shuffle.__doc__
x, random=random.random -> shuffle list x in place; return None.

        Optional arg random is a 0-argument function returning a random
        float in [0.0, 1.0); by default, the standard random.random.

        Note that for even rather small len(x), the total number of
        permutations of x is larger than the period of most random number
        generators; this implies that "most" permutations of a long
        sequence can never be generated.

>>>

Unless the underlying generator has at least 52! distinct internal states,
it's incapable of generating all the permutations, no matter how cleverly
you apply it (the final outcome is wholly determined by the particular
internal state it has when you begin).  The link above points to a generator
with as much internal state as you can bear to use <wink>.






More information about the Python-list mailing list