Unsorting(randomizing) a sequence
Magnus L. Hetland
mlh at idt.ntnu.no
Fri Aug 20 15:30:59 EDT 1999
Chad Netzer <chad at vision.arc.nasa.gov> writes:
> Christopher Browne wrote:
[...]
> The solution posted previously by Dan Schmidt, should work (I'll translate
> to C pseudocode to match the above form):
>
> for (i = n; i > 0; i--)
> {
> j = i -1;
> swap(item[j], item[random(j)]); /* choose from remaining items in list */
> }
Which would be, in Python:
from random import randint
def shuffle(list):
for x in range(len(list)-1,0,-1):
y = randint(0,x-1)
list[x],list[y] = list[y],list[x]
Is that among the suggested solutions? (Sorry for not really paying
attention... ;)
At least it's short...
--
Magnus Making no sound / Yet smouldering with passion
Lie The firefly is still sadder / Than the moaning insect
Hetland : Minamoto Shigeyuki
More information about the Python-list
mailing list