Re: shuffling elements of a list
- From: Fredrik Lundh <fredrik@xxxxxxxxxxxxxx>
- Date: Wed, 31 May 2006 23:05:14 +0200
Roger Miller wrote:
DSU seems like a lot of trouble to go through in order to use an O(n
log n) sorting algorithm to do what can be done in O(N) with a few
lines of code. The core code of random.shuffle() shows how easy it is
to do it right:
for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]
easy to do it right? you know, the main reason for adding shuffle to the standard library was that its way too easy to get it wrong.
see e.g. this thread: http://tinyurl.com/ppgzq
</F>
.
- References:
- shuffling elements of a list
- From: greenflame
- Re: shuffling elements of a list
- From: Ben Finney
- Re: shuffling elements of a list
- From: greenflame
- Re: shuffling elements of a list
- From: David C . Ullrich
- Re: shuffling elements of a list
- From: Sybren Stuvel
- Re: shuffling elements of a list
- From: Roger Miller
- shuffling elements of a list
- Prev by Date: Re: using import * with GUIs?
- Next by Date: Re: Save data to a file thru a http connection
- Previous by thread: Re: shuffling elements of a list
- Next by thread: Re: shuffling elements of a list
- Index(es):