在Python组分区 [英] Set partitions in Python

查看:184
本文介绍了在Python组分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的数组[1,2,3]

我想要使用阵列中的所有元素所有可能的组合:

结果:

  [1],[2],[3]
[[1,2],[3]
[1],[2,3]]
[[1,3],[2]
[[1,2,3]]


解决方案

由于这个漂亮的问题已经被带回的生活,这里是一个新鲜的答案。

问题是递归解决:如果你已经拥有的 N-1 的元素,你怎么用它分区划分的 N 的元素呢?无论是放置的 N 的现有子集中的一'个元素,或将其添加为新的单集。这一切都需要;没有和itertools ,不套,不重复的输出,总共才的 N 的调用分区()

 高清分区(集合):
    如果len(集合)== 1:
        产量[收藏]
        返回    首先收集= [0]
    在小分区(集合[1:]):
        #在每个子分区的子集插入`first`
        对于n,子集枚举(小):
            产生较小[:N] + [首页] +子集] +小[N + 1:]
        #`摆在first`自己的子集
        产量[[首页]] +小
东西=名单(范围(1,5))氮,磷在枚举(分区(东西),1):
    打印(N,排序(P))

输出:

  1 [[1​​,2,3,4]]
2 [1],[2,3,4]]
3 - [[1,2],[3,4]
4 - [[1,3,4],[2]
5 [1],[2],[3,4]]
6 - [[1,2,3],[4]
7 [[1,4],[2,3]]
8 [1],[2,3],[4]
9 [[1,3],[2,4]
10 [[1,2,4],[3]
11 [1],[2,4],[3]
12 [[1,2],[3],[4]
13 [[1,3],[2],[4]
14 [[1,4],[2],[3]
15 [1],[2],[3],[4]

I have an array of [1,2,3]

I want to make all the possible combinations using all elements of the array:

Result:

[[1], [2], [3]]
[[1,2], [3]]
[[1], [2,3]]
[[1,3], [2]]
[[1,2,3]]

解决方案

Since this nice question has been brought back to life, here's a fresh answer.

The problem is solved recursively: If you already have a partition of n-1 elements, how do you use it to partition n elements? Either place the n'th element in one of the existing subsets, or add it as a new, singleton subset. That's all it takes; no itertools, no sets, no repeated outputs, and a total of just n calls to partition():

def partition(collection):
    if len(collection) == 1:
        yield [ collection ]
        return

    first = collection[0]
    for smaller in partition(collection[1:]):
        # insert `first` in each of the subpartition's subsets
        for n, subset in enumerate(smaller):
            yield smaller[:n] + [[ first ] + subset]  + smaller[n+1:]
        # put `first` in its own subset 
        yield [ [ first ] ] + smaller


something = list(range(1,5))

for n, p in enumerate(partition(something), 1):
    print(n, sorted(p))

Output:

1 [[1, 2, 3, 4]]
2 [[1], [2, 3, 4]]
3 [[1, 2], [3, 4]]
4 [[1, 3, 4], [2]]
5 [[1], [2], [3, 4]]
6 [[1, 2, 3], [4]]
7 [[1, 4], [2, 3]]
8 [[1], [2, 3], [4]]
9 [[1, 3], [2, 4]]
10 [[1, 2, 4], [3]]
11 [[1], [2, 4], [3]]
12 [[1, 2], [3], [4]]
13 [[1, 3], [2], [4]]
14 [[1, 4], [2], [3]]
15 [[1], [2], [3], [4]]

这篇关于在Python组分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆