# 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 """ result = ['owl', 'olw', 'wol', 'wlo', 'low', 'lwo'] ['art', 'atr', 'rat', 'rta', 'tar', 'tra'] items in bush list = 24 items in bush set = 24 items in tart list = 24 items in tart set = 12 [7, 8, 9] [7, 9, 8] [8, 7, 9] [8, 9, 7] [9, 7, 8] [9, 8, 7] """
Are you able to help answer this sponsored question?
Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.