• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

can someone explain this code to me? (permutation written in python)

jread

Senior member
Found this on another site and just wanted to understand how it is working. I get lost once it starts looking for "k" in the range. I'm not sure what values it is selecting and how it is arranging them.

Thanks! 🙂


# a simple recursive permutation function
# the number of permutations of a sequence of n unique items is given by n! (n factorial)
# more details at http://mathworld.wolfram.com/Permutation.html
# tested with Python24 vegaseat 16feb2006

def permutate(seq):
"""permutate a sequence and return a list of the permutations"""
if not seq:
return [seq] # is an empty sequence
else:
temp = []
for k in range(len(seq)):
part = seq[:k] + seq[k+1:]
#print k, part # test
for m in permutate(part):
temp.append(seq[k:k+1] + m)
#print m, seq[k:k+1], temp # test
return temp

# test the module
if __name__ == "__main__":
# permutate a string, how many recognizable words does this generate?
print permutate('owl')
print permutate('art')
# test for duplicates
blist = permutate('bush')
print "items in bush list =", len(blist) # should be 4! or 1*2*3*4 = 24
print "items in bush set =", len(set(blist)) # should be the same
tlist = permutate('tart')
print "items in tart list =", len(tlist) # should be 4! or 1*2*3*4 = 24
print "items in tart set =", len(set(tlist)) # less unique since there are two 't'
# permutate a list
list1 = [7, 8, 9]
for list2 in permutate(list1):
print list2
 
Back
Top