Unsorting(randomizing) a sequence
Skip Montanaro
skip at mojam.com
Tue Aug 17 10:43:37 EDT 1999
Ole> I've been writing an algorithm myself, but it's incredibly slow and
Ole> I would like something quicker (of course :) )
Got this off the list a couple years ago. Does the trick for me:
def shuffle(lst):
"randomize a list"
for i in range(len(lst)-1,0,-1):
choice = int(whrandom.random() * i)
lst[choice], lst[i] = lst[i], lst[choice]
>>> l = range(20)
>>> shuffle(l)
>>> l
[4, 17, 12, 6, 7, 15, 1, 11, 16, 10, 5, 3, 9, 19, 0, 8, 18, 13, 14, 2]
Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/~skip/
847-971-7098
More information about the Python-list
mailing list