Is there such a beast as a "perfect" shuffle? :)
Ian Bicking
ianb at colorstudy.com
Mon May 13 04:04:21 EDT 2002
I'm late on the thread, but perhaps this is better:
def shuffle(l):
l = [(random.random(), i) for i in l]
l.sort()
return [i for r, i in l]
If you use a real random number generator (e.g., /dev/urandom), instead
of random's pseudo-random generator, then you will be able to receive
the full len(l)! possibilities. The precision of floats will lead to a
certain amount of non-randomness, with large enough l. Perhaps you
could do something like:
l.sort(lambda a, b: cmp(a[0], b[0]) or random.randrange(-1, 2))
I don't know what the distribution of this looks like:
def shuffle(l):
l = l[:]
l.sort(lambda a, b: cmp(random.randrange(-1, 2))
return l
I guess it depends on sort's algorithm. A nondeterministic sort is kind
of odd to think about.
Ian
More information about the Python-list
mailing list