Finding all possible combination of all possible subsets of lists

ぃ、小莉子 提交于 2019-12-23 05:29:14

问题


I am trying to find all combinations of subsets of from a list, where each element is used only once.

To clarify what I mean, given an example list of:

[1, 2, 3, 4]

I can generate, the following combinations:

[(1), (2), (3), (1, 2), (1, 3), (2, 3), (1, 2, 3)] (this should be exhaustive!)

Then I can generate combinations of these combinations:

[[(1), (2), (3)], [(1, 2), (3)], [(1, 3), (2)], [(1), (2, 3)],[(1, 2, 3)],... (for many)]

The main point is that I am only allowed to use each element once, in a given combination. So I cannot have:

[(1), (1, 2, 3)] because element 1 is used twice.

I have been trying to brute force for small n (n < 10), and have been failing, using python. At this point it is not even a runtime problem (small n!), but I am not even finding all the possibilities!

I am not sure that I am formulating my question very well, so please ask clarify questions. Also, if there are certain key words to help me clarify the question, do tell! I am interested in a Python approach - but am open to any MATH approaches to help me do this. Runtime is an issue that I hope to tackle later!

Thanks!

Edit 1: Another way of viewing this question is with the subset sum problem, but caveat 1: not just find all possible subsets, but find all sets of combination of subsets such that, the most number of elements of the original list is used, where each individual subset sums to 0 (or k).

My goal is to then loop through all answers and score them based on how many elements were ultimately unused and pick a "best" set of subsets.'

Edit 2: accepted answer, but modified to accept a user created list myList = ['a', 'b', 'c', 'd']

def partitions(myList):
   if not myList:
       yield []
   else:
       for partial_partition in partitions(myList[:-1]):
           for i in range(len(partial_partition)):
               copy_partition = partial_partition[:]
               copy_partition[i] += (myList[-1],)
               yield copy_partition
           yield partial_partition + [(myList[-1],)]

回答1:


Recursion! Generate all possible partitions of 1..n, then use those to generate all possible partitions of 1..n+1:

def partitions(n):
    if n == 0:
        yield []
    else:
        for partial_partition in partitions(n-1):
            for i in range(len(partial_partition)):
                copy_partition = partial_partition[:]
                copy_partition[i] += (n,)
                yield copy_partition
            yield partial_partition + [(n,)]


来源:https://stackoverflow.com/questions/19169678/finding-all-possible-combination-of-all-possible-subsets-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!