1 from __future__ import generators
7 Generators for calculating a) the permutations of a sequence and
8 b) the combinations and selections of a number of elements from a
9 sequence. Uses Python 2.2 generators.
11 Similar solutions found also in comp.lang.python
13 Keywords: generator, combination, permutation, selection
15 See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962
16 See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66463
17 See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66465
21 def xcombinations(items, n):
24 for i in xrange(len(items)):
25 for cc in xcombinations(items[:i]+items[i+1:],n-1):
28 def xuniqueCombinations(items, n):
31 for i in xrange(len(items)):
32 for cc in xuniqueCombinations(items[i+1:],n-1):
35 def xselections(items, n):
38 for i in xrange(len(items)):
39 for ss in xselections(items, n-1):
42 def xpermutations(items):
43 return xcombinations(items, len(items))
45 if __name__=="__main__":
46 print "Permutations of 'love'"
47 for p in xpermutations(['l','o','v','e']): print ''.join(p)
50 print "Combinations of 2 letters from 'love'"
51 for c in xcombinations(['l','o','v','e'],2): print ''.join(c)
54 print "Unique Combinations of 2 letters from 'love'"
55 for uc in xuniqueCombinations(['l','o','v','e'],2): print ''.join(uc)
58 print "Selections of 2 letters from 'love'"
59 for s in xselections(['l','o','v','e'],2): print ''.join(s)
62 print map(''.join, list(xpermutations('done')))