Tuple subsets

I want to give the following:

(('A',), ('B',), ('C',), ('D',)) (('A',), ('B',), ('C','D')) (('A',), ('B','C'), ('D',)) (('A',), ('B','C','D')) (('A','B'), ('C',), ('D',)) (('A','B'), ('C','D')) (('A','B','C'), ('D',)) (('A','B','C','D'),) 

when calling sub_combinations(('A', 'B', 'C', 'D'))

Here is my attempt, but it does not work:

 def sub_combinations(segment): for i in range(1, len(segment)): for j in sub_combinations(segment[i:]): yield segment[:i]+j yield segment 

but I think I'm on the right track.

In addition, I would like the second argument to be called a limit that limits the size of the subsets, for example sub_combinations(('A', 'B', 'C', 'D'), 2) :

 (('A',), ('B',), ('C',), ('D',)) (('A',), ('B',), ('C','D')) (('A',), ('B','C'), ('D',)) (('A','B'), ('C',), ('D',)) (('A','B'), ('C','D')) 

I am using python 3.

+6
source share
2 answers

Process base register - when segment empty:

 def sub_combinations(segment, size=0): if segment == (): yield () return stop = min(size or len(segment), len(segment)) for i in range(1, stop + 1): for j in sub_combinations(segment[i:], size): yield (segment[:i],) + j 

Usage example:

 >>> for x in sub_combinations(('A', 'B', 'C', 'D')): ... print(x) ... (('A',), ('B',), ('C',), ('D',)) (('A',), ('B',), ('C', 'D')) (('A',), ('B', 'C'), ('D',)) (('A',), ('B', 'C', 'D')) (('A', 'B'), ('C',), ('D',)) (('A', 'B'), ('C', 'D')) (('A', 'B', 'C'), ('D',)) (('A', 'B', 'C', 'D'),) 

 >>> for x in sub_combinations(('A', 'B', 'C', 'D'), 2): ... print(x) ... (('A',), ('B',), ('C',), ('D',)) (('A',), ('B',), ('C', 'D')) (('A',), ('B', 'C'), ('D',)) (('A', 'B'), ('C',), ('D',)) (('A', 'B'), ('C', 'D')) 
+7
source

If you can also live with lists instead of tuples (or not be afraid to convert them later), you can use this:

 def subtuples(t): for i in range(1<< (len(t)-1)): result = [ [ t[0] ] ] for j in range(len(t)-1): if (1<<j) & i: result[-1].append(t[j+1]) else: result.append([ t[j+1] ]) yield result for x in subtuples(('a', 'b', 'c', 'd')): print(x) 
+3
source

All Articles