gpt4 book ai didi

python - 在 Python 中设置分区

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:16 25 4
gpt4 key购买 nike

我有一个数组[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com