11"""Generators for combinations and permutations.
13This module contains functions for
14generating all combinations and permutations from a list of
15items. These functions return generators, so you may iterate
16over them or retrieve successive values with
17next(). Given a sequence items,
18you can iterate over the list of unique pairwise combinations with
20 for (i1, i2) in combo.xuniqueCombinations (items, 2):
22The functions contained in this module are:
25 Yields all unique subsequences of length n from items.
27 all_combinations(items,n)
28 Similar, but differences in ordering are considered significant.
29 For example, all_combinations([1,2,3],2) will yield both [1,2] and [2,1].
32 Yields all permutations of items.
33 Equivalent to all_combinations(items,len(items)).
36 Returns all possible ways of picking n items from
37 items, where any given item may be picked multiple times.
40from builtins
import range
44Generators for calculating a) the permutations of a sequence and
45b) the combinations and selections of a number of elements from a
46sequence. Uses Python 2.2 generators.
48Similar solutions found also in comp.lang.python
50Keywords: generator, combination, permutation, selection
52See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962
53See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66463
54See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66465
58 """Return all subsequences of length n from items.
59Differences in ordering are considered significant.
60For example, all_combinations([1,2,3],2) will yield both [1,2] and [2,1].
62>>> for c in all_combinations(['l','o','v','e'],2):
80 for i
in range(len(items)):
85 """Yields all unique subsequences of length n from items.
87>>> for uc in combinations(['l','o','v','e'],2):
88... print (''.join(uc))
99 for i
in range(len(items)):
104 """Returns all possible ways of picking n items from
105items, where any given item may be picked multiple times.
107>>> for s in selections(['l','o','v','e'],2):
108... print (''.join(s))
129 for i
in range(len(items)):
134 """ Yields all permutations of items.
135Equivalent to all_combinations(items,len(items)).
137>>> for p in permutations(['l','o','v','e']):
138... print (''.join(p))
168__test__[
'tests'] =
"""
169>>> # Permutations of 'love'
170>>> print (list(map(''.join, list(permutations('done')))))
171['done', 'doen', 'dnoe', 'dneo', 'deon', 'deno', 'odne', 'oden', 'onde', 'oned', 'oedn', 'oend', 'ndoe', 'ndeo', 'node', 'noed', 'nedo', 'neod', 'edon', 'edno', 'eodn', 'eond', 'endo', 'enod']
175if __name__ ==
"__main__":
176 print (
'PyAnalysisUtils/combo.py test')
all_combinations(items, n)