python - 在 Python 中设置分区

标签 python arrays combinatorics

我有一个数组[1,2,3]

我想使用数组的所有元素进行所有可能的组合:

结果:

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

最佳答案

既然这个好问题已经复活,这里有一个新的答案。

问题递归解决:如果你已经有了一个n-1个元素的分区,你如何用它来分区n个元素?要么将第 n 个元素放入现有子集中,要么将其添加为新的单独子集。仅此而已;没有 itertools,没有集合,没有重复输出,总共只有 npartition() 调用:

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))

输出:

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 - 在 Python 中设置分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47985470/

相关文章:

javascript - 从数组创建对象数组

c++ - C++中的组合数(N选R)

c#输出可能的路线

python - 在什么情况下需要像python-opencv中的reshape(-1,1,2)那样 reshape 点?

python - 使用 tkinter 时,与 "root"和 "master"的结果相同。那么,什么时候使用每一个呢?

python - pyodbc 版本是什么?

python - 如何构建一个 N*(N+1) 矩阵,其数量在 1~N*N 范围内且完全分布?

python - “If”语句和来自命令行的一行 Python 脚本

javascript - 如何将数组转换为 Backbone 中的集合

java - 小程序输出错误。为什么这个字符串变量没有按照我想要的方式执行?