Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean in the docs for random.shuffle?

Tags:

python

random

http://docs.python.org/2/library/random.html#random.shuffle

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function 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.

Can someone please explain to me what the last sentence means?

It sounds like maybe there's a limit to the size of list that you can or should use shuffle on?

like image 324
Anentropic Avatar asked Jan 22 '14 13:01

Anentropic


People also ask

What does random shuffle mean?

random. shuffle(x, random) It means shuffle a sequence x using a random function.

What is from random import shuffle?

The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling a list of objects means changing the position of the elements of the sequence using Python.

How do you randomly shuffle a string?

To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.


1 Answers

It means that for longer lists, the random number generator will start repeating itself, so that the number of different possible 'shuffles' for a given list is not going to be the number of permutations of the list.

For a list of length N, there are N! (N factorial) possible ways to permute the list order, but if the random generator starts repeating itself after fewer than N! iterations, then the random.shuffle() function will not be able to produce all N! permutations for that list.

It'll still be able to shuffle the list, but even if you shuffled the list an infinite number of times, it will not produce all possible orderings for such a list.

The default random.random() function uses the Mersenne Twister algorithm, which has a period of 2**19937-1. That means that you'd need a list of length 2081 before you will see this behaviour occur.

like image 189
Martijn Pieters Avatar answered Nov 28 '22 23:11

Martijn Pieters