6

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?

das-g
  • 9,718
  • 4
  • 38
  • 80
  • `np`.... are you also using _NumPy_? – CristiFati Mar 09 '17 at 21:07
  • 5
    Possible duplicate of [Set partitions in Python](http://stackoverflow.com/questions/19368375/set-partitions-in-python) – Alex Hall Mar 09 '17 at 21:17
  • @AlexHall I think that the focus on `itertools` is enough to make this a non-duplicate. Itertools seems like it has the necessary tools but it isn't clear how those tools can be combined to get a good solution for this. – John Coleman Mar 09 '17 at 21:48
  • @JohnColeman The top answer shows how to do it primarily with itertools and also that doing so is a bad idea. – Alex Hall Mar 09 '17 at 21:52
  • @AlexHall The top answer doesn't use itertools. The other answer does, but the author of it refers to it as slow. It seems like there is room for improvement. Maybe there isn't, but it doesn't hurt to ask. – John Coleman Mar 09 '17 at 21:59

2 Answers2

-1
a = [1, 2, 3]
b = list()
for l in range(len(a)+1): b.append([c for c in combinations(a, l)])

print(b)

check this

shiyon sufa
  • 179
  • 3
  • 7
-1

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
DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • Your `partition(list(range(4)))` does not generate `[[0, 1], [2, 3]]`. Choose one of the methods from [the thread that Alex Hall linked above](http://stackoverflow.com/questions/19368375/set-partitions-in-python) instead. – Dennis Feb 27 '20 at 18:21