
On Sun, 19 Nov 2000, Daniel Yoo wrote:
This looks nice! It might be nice to show another approach to shuffling the alphabet:
### from string import uppercase from random import randint def permute(L): """ Permute a list by swapping elements randomly. """ newlist = L[:] # shallow copy for i in range(len(L)): rand_i = randint(i, len(L)-1) newlist[i], newlist[rand_i] = newlist[rand_i], newlist[i] return newlist
if __name__ == '__main__': print permute(list(uppercase)) ###
It takes a bit more thought to see that this acheives the same amount of permutation as the original. For instance, if we merely swapped random elements L times, the result would be different, because unchanged elements would be much more common. That is: ### from string import uppercase from random import randint def permute(L): """ Permute a list by swapping elements randomly. """ newlist = L[:] # shallow copy for i in range(len(L)/2+1): rand_i = randint(0, len(L)-1) rand_j = randint(0, len(L)-1) newlist[rand_j], newlist[rand_i] = newlist[rand_i], newlist[rand_j] return newlist if __name__ == '__main__': print permute(list(uppercase)) ### I can see some interesting discussions about what it means to be random, and what sorts of characteristics we might want from a 'random' activity in different situations. --------------------------------------------------------------------- | Connection - in an isolating age )O( | ---------------------------------------------------------------------