diff options
author | Guido van Rossum <guido@python.org> | 1999-08-18 13:53:28 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 1999-08-18 13:53:28 (GMT) |
commit | 6c395ba31609eeffce2428280cc5d95e4fb8058a (patch) | |
tree | cf7c39412c70b26dd3d53d5041e960f8e3d8db98 /Lib | |
parent | e393ddb2e05836be79f4fc34ed26ff217074c967 (diff) | |
download | cpython-6c395ba31609eeffce2428280cc5d95e4fb8058a.zip cpython-6c395ba31609eeffce2428280cc5d95e4fb8058a.tar.gz cpython-6c395ba31609eeffce2428280cc5d95e4fb8058a.tar.bz2 |
Add Tim Peters' shuffle() algorithm.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/random.py | 21 |
1 files changed, 21 insertions, 0 deletions
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): |