[Edu-sig] Cryptonomicon

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 19 Nov 2000 19:32:53 -0800 (PST)


> def permute():
>     """
>     Randomly permute the uppercase alphabet
>     by choosing its letters pseudo-randomly
>     """
>     alphalist = list(string.uppercase)
>     newlist = []
>     for i in range(len(alphalist)):
>         randchar = random.choice(alphalist)
>         alphalist.remove(randchar)
>         newlist.append(randchar)
>     return newlist


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))
###