Search code examples
pythonpython-itertools

get all the partitions of the set python with itertools


How to get all partitions of a set?

For example, I have array [1, 2, 3]. I need to get [[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]].

Now, I wrote this code:

def neclusters(S, K):
    for splits in itertools.combinations(range(len(S)), K):
       yield np.split(S, 1 + np.array(splits))

But that code don't return [[2],[1,3]].

I could take all permutations of the original set and run this code on them. But can this be made easier?


Solution

  • I wrote this one for fun:

    def partition(a_list):
        yield [[x] for x in a_list]   
        for i in range(1, len(a_list) + 1):
            _l = a_list[:]
            yield [_l.pop(i-1), _l]
        yield a_list
    
    my_list = [1, 2, 3]
    print list(partition(my_list))
    
    #or
    
    for p in partition(my_list):
        print p