Discussion:
Simple algorithm question - how to reorder a sequence economically
(too old to reply)
Peter Brooks
2013-05-24 08:14:45 UTC
Permalink
What is the easiest way to reorder a sequence pseudo-randomly?

That is, for a sequence 1,2,3,4 to produce an arbitrary ordering (eg
2,1,4,3) that is different each time.

I'm writing a simulation and would like to visit all the nodes in a
different order at each iteration of the simulation to remove the risk
of a fixed order introducing spurious evidence of correlation.
Steven D'Aprano
2013-05-24 10:52:18 UTC
Permalink
Post by Peter Brooks
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.
Post by Peter Brooks
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
Loading...