Package TEES :: Package Utils :: Package Libraries :: Module combine
[hide private]

Source Code for Module TEES.Utils.Libraries.combine

 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   
21 -def combine(*seqin):
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: # any more sequences to process? 28 for item in seqin[0]: 29 newcomb=comb+[item] # add next item to current comb 30 # call rloop w/ rem seqs, newcomb 31 rloop(seqin[1:],listout,newcomb) 32 else: # processing last sequence 33 listout.append(comb) # comb finished, add to list
34 listout=[] # listout initialization 35 rloop(seqin,listout,[]) # start recursive process 36 return listout 37
38 -def xcombine(*seqin):
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: # any more sequences to process? 47 for item in seqin[0]: 48 newcomb=comb+[item] # add next item to current combination 49 # call rloop w/ remaining seqs, newcomb 50 for item in rloop(seqin[1:],newcomb): 51 yield item # seqs and newcomb 52 else: # processing last sequence 53 yield comb # comb finished, add to list
54 return rloop(seqin,[]) 55