From <python cookbook> 19.15
Task
You need to iterate over the arrangement (permutation), composition (combination), or selection (selection) of a sequence. Even though the initial sequence length is not long, the rules for combining calculations show that the resulting sequence can be very large, such as a sequence of length 13 has more than 6 billion possible permutations. So, you certainly don't want to calculate and generate all the items in the sequence before you start the iteration
Solution Solutions
The generator allows you to compute the desired object at the time of the iteration. If you have many of these objects and you have to check them individually, it can take a long time for the program to complete the loop. But at least you don't have to waste a lot of memory to save all the items:
def_combinators (_handle, items, N):" "extract the general structure of the following combinations" " ifn = =0:yield [ ] forI, iteminchEnumerate (items): This_one=[item] forCcinch_combinators (_handle, _handle (items, i), n-1): yieldThis_one +ccdefcombinations (items, n):" "get n different items, order is meaningful" " defSkipithitem (items, i):returnITEMS[:I] + items[i + 1:] return_combinators (Skipithitem, items, N)defuniquecombinations (items, N):" "get n different items, order-independent" " defAfterithitem (items, i):returnItems[i+1:] return_combinators (Afterithitem, items, N)defselections (items, n):" "Get n items (not necessarily different), order is meaningful" " defkeepallitems (items, i):returnItemsreturn_combinators (keepallitems, items, N)defpermutations (items):" "get all the items, the order is meaningful" " returncombinations (items, Len (items))if __name__=='__main__': Print "permutations of ' bar '" PrintMap"'. Join, permutations ('Bar'))#output: [' bar ', ' bra ', ' abr ', ' arb ', ' RBA ', ' rab '] Print "combinations of 2 letters from ' Bar '" PrintMap"'. Join, combinations ('Bar', 2))#output: [' ba ', ' BR ', ' ab ', ' ar ', ' RB ', ' RA '] Print "Unique combinations of 2 letters from ' Bar '" PrintMap"'. Join, Uniquecombinations ('Bar', 2))#output: [' ba ', ' br ', ' ar '] Print "selections of 2 letters from ' Bar '" Print["'. Join, Selections ('Bar', 2)]#output: [' BB ', ' ba ', ' BR ', ' ab ', ' AA ', ' ar ', ' RB ', ' Ra ', ' RR ']
Python generates permutations, combinations, and selections