Simple algorithm question - how to reorder a sequence economically
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 24 06:52:18 EDT 2013
On Fri, 24 May 2013 01:14:45 -0700, Peter Brooks wrote:
> What is the easiest way to reorder a sequence pseudo-randomly?
import random
random.shuffle(sequence)
The sequence is modified in place, so it must be mutable. Lists are okay,
tuples are not.
> That is, for a sequence 1,2,3,4 to produce an arbitrary ordering (eg
> 2,1,4,3) that is different each time.
You can't *guarantee* that it will be different each time. With a four-
item list, there are only 4! = 24 combinations, so on average you'll get
the original order one time in 24. For a ten-item list, that is once
every 3628800 times, and for a twenty-item list, once in
2432902008176640000 times. But of course these are *random*, and there's
always a chance of this:
http://dilbert.com/strips/comic/2001-10-25
--
Steven
More information about the Python-list
mailing list