1 """
2 Combinations from multiple sequences
3
4 Source: ASPN: Python Cookbook
5 Title: Generating combinations of objects from multiple sequences
6 Submitter: David Klaffenbach (other recipes)
7 Last Updated: 2004/08/29
8 Version no: 1.0
9 Category: Algorithms
10
11 Description:
12
13 The function combine takes multiple sequences and creates a list in which
14 each item is constructed from items from each input sequence, and all possible
15 combinations are created. If that description is confusing, look at the
16 example in the docstring. It's a pretty simple transformation. The function
17 xcombine is similar, but returns a generator rather than creating the output
18 all at once.
19 """
20
22 '''returns a list of all combinations of argument sequences.
23 for example: combine((1,2),(3,4)) returns
24 [[1, 3], [1, 4], [2, 3], [2, 4]]'''
25 def rloop(seqin,listout,comb):
26 '''recursive looping function'''
27 if seqin:
28 for item in seqin[0]:
29 newcomb=comb+[item]
30
31 rloop(seqin[1:],listout,newcomb)
32 else:
33 listout.append(comb)
34 listout=[]
35 rloop(seqin,listout,[])
36 return listout
37
39 '''returns a generator which returns combinations of argument sequences
40 for example xcombine((1,2),(3,4)) returns a generator; calling the next()
41 method on the generator will return [1,3], [1,4], [2,3], [2,4] and
42 StopIteration exception. This will not create the whole list of
43 combinations in memory at once.'''
44 def rloop(seqin,comb):
45 '''recursive looping function'''
46 if seqin:
47 for item in seqin[0]:
48 newcomb=comb+[item]
49
50 for item in rloop(seqin[1:],newcomb):
51 yield item
52 else:
53 yield comb
54 return rloop(seqin,[])
55