[Edu-sig] More permutation madness [Cryptonomicon]

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 30 Nov 2000 03:33:55 -0800 (PST)


  This message is in MIME format.  The first part should be readable text,
  while the remaining parts are likely unreadable without MIME-aware tools.
  Send mail to mime@docserver.cac.washington.edu for more info.

--545289610-2108799327-975584035=:15623
Content-Type: TEXT/PLAIN; charset=US-ASCII


There was a question about ways of generating permutations: is there an
easy way to show that these two functions:

###
def permuteRestricted(L):
    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

def permuteUnrestricted(L):
    newlist = L[:]   # shallow copy            
    for i in range(len(L)):                   
        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
###

act differently?

I tried to prove this difference by brute force: the attached program
generates the whole space of permutations, given these two methods.  I
have to apologize for the code's uglyness and sluggishness, and if anyone
can simplify or optimize it, I'd be very happy.

I hope this helps!

--545289610-2108799327-975584035=:15623
Content-Type: TEXT/PLAIN; charset=US-ASCII; name="countPerms.py"
Content-Transfer-Encoding: BASE64
Content-ID: <Pine.LNX.4.21.0011300333550.15623@hkn.eecs.berkeley.edu>
Content-Description: 
Content-Disposition: attachment; filename="countPerms.py"

IiIiVGhpcyBpcyBhIHNtYWxsIHNjcmlwdCB0aGF0IHNob3dzIHRoZSBkaWZm
ZXJlbmNlIGJldHdlZW4gdHdvDQpzaHVmZmxpbmcgbWV0aG9kcy4gIEl0IHNo
b3VsZCBzaG93IHRoYXQgb25lIGFwcHJvYWNoIGRvZXNuJ3QgZXZlbmx5DQpn
ZW5lcmF0ZSBjZXJ0YWluIHR5cGVzIG9mIHNodWZmbGluZy4NCg0KRG8gdGhl
IGZvbGxvd2luZyBmdW5jdGlvbnM6DQoNCiMjIw0KZGVmIHBlcm11dGVSZXN0
cmljdGVkKEwpOg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