[Tutor] Permutations?

Hee-Seng Kye kyeser at earthlink.net
Sun Jul 25 09:40:00 CEST 2004


def perm(k):
     # Compute the list of all permutations of k
     if len(k) <= 1:
         return [k]
     r = []
     for i in range(len(k)):
         s =  k[:i] + k[i+1:]
         p = perm(s)
         for x in p:
             r.append(k[i:i+1] + x)
     return r

Could someone tell me how I can modify the above function so that it 
produces a list of permutations of k that only begins on k[0]?

If k = [0,1,2,3], I want to modify perm(k) so that it only produces 
[[0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1]].

I could produce the list of ALL permutations of k and then delete the 
ones which don't begin with k[0], but for a large list, this could 
really slow things down.  I was thinking of algorithm that computes 
only the ones I want.

I would appreciate anyone's suggestion.  Thanks.

Best,
Kye

p.s. By the way, does anyone have any idea if it would drive my 
computer (667 MHz and 512MB RAM) nuts to perm(range(12))?



More information about the Tutor mailing list