From 6c395ba31609eeffce2428280cc5d95e4fb8058a Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Wed, 18 Aug 1999 13:53:28 +0000 Subject: Add Tim Peters' shuffle() algorithm. --- Lib/random.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Lib/random.py b/Lib/random.py index 9ec41e1..9e899ad 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -292,6 +292,27 @@ def weibullvariate(alpha, beta): u = random() return alpha * pow(-log(u), 1.0/beta) +# -------------------- shuffle -------------------- +# Not quite a random distribution, but a standard algorithm. +# This implementation due to Tim Peters. + +def shuffle(x, random=random, int=int): + """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. + """ + + for i in xrange(len(x)-1, 0, -1): + # 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] + # -------------------- test program -------------------- def test(N = 200): -- cgit v0.12