get all the partitions of the set python with itertools

帅比萌擦擦* 提交于 2020-12-10 03:31:42

问题


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?


回答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



回答2:


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



来源:https://stackoverflow.com/questions/42704932/get-all-the-partitions-of-the-set-python-with-itertools

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