]> AND Private Git Repository - 14Mons.git/blob - experiments/combinaisons.py
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
initiailisation
[14Mons.git] / experiments / combinaisons.py
1 from __future__ import generators
2 #!/usr/bin/env python
3
4 __version__ = "1.0"
5
6 """xpermutations.py
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.
10
11 Similar solutions found also in comp.lang.python
12
13 Keywords: generator, combination, permutation, selection
14
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
18 """
19
20
21 def xcombinations(items, n):
22     if n==0: yield []
23     else:
24         for i in xrange(len(items)):
25             for cc in xcombinations(items[:i]+items[i+1:],n-1):
26                 yield [items[i]]+cc
27
28 def xuniqueCombinations(items, n):
29     if n==0: yield []
30     else:
31         for i in xrange(len(items)):
32             for cc in xuniqueCombinations(items[i+1:],n-1):
33                 yield [items[i]]+cc
34             
35 def xselections(items, n):
36     if n==0: yield []
37     else:
38         for i in xrange(len(items)):
39             for ss in xselections(items, n-1):
40                 yield [items[i]]+ss
41
42 def xpermutations(items):
43     return xcombinations(items, len(items))
44
45 if __name__=="__main__":
46     print "Permutations of 'love'"
47     for p in xpermutations(['l','o','v','e']): print ''.join(p)
48
49     print
50     print "Combinations of 2 letters from 'love'"
51     for c in xcombinations(['l','o','v','e'],2): print ''.join(c)
52
53     print
54     print "Unique Combinations of 2 letters from 'love'"
55     for uc in xuniqueCombinations(['l','o','v','e'],2): print ''.join(uc)
56
57     print
58     print "Selections of 2 letters from 'love'"
59     for s in xselections(['l','o','v','e'],2): print ''.join(s)
60
61     print
62     print map(''.join, list(xpermutations('done')))