如何使用python中的一组标签生成所有可能的标记(分类)一组对象的方法?

问题描述 投票:2回答:2

假设我们有一组对象:

set_of_objects = {1, 2, 3, 4, 5}

和一组课程:

set_of_classes = {'a', 'b', 'c'}

我们如何在python的类集中生成所有对象集合的所有可能类的分类方法?

示例输出将是这样的:

[[1],[2],[3]]
[[1,2],[3],[]]
[[1,2,3],[],[]]
[[3],[2],[1]]
and so on...

我们可以将n个对象分类为k个类的所有方法的数量是:k ^ n,因为我们可以将n个对象中的每一个分配到k个类中。

python combinations
2个回答
1
投票

您可以制作递归算法来生成分区:

import itertools

def part(lst, n):
    if n <= 1:
        # single answer for 1 partition
        yield [lst]
    else:
        for m in range(len(lst)+1):
            for head in itertools.combinations(lst, m):
                nothead = [x for x in lst if x not in head]
                for tail in part(nothead, n-1):
                    yield [list(head)]+tail

def partition(n):
    lst = list(range(n))
    for x in part(lst, n):
        print(x)

示例:partition(3)

[[], [], [0, 1, 2]]
[[], [0], [1, 2]]
[[], [1], [0, 2]]
[[], [2], [0, 1]]
[[], [0, 1], [2]]
[[], [0, 2], [1]]
[[], [1, 2], [0]]
[[], [0, 1, 2], []]
[[0], [], [1, 2]]
[[0], [1], [2]]
[[0], [2], [1]]
[[0], [1, 2], []]
[[1], [], [0, 2]]
[[1], [0], [2]]
[[1], [2], [0]]
[[1], [0, 2], []]
[[2], [], [0, 1]]
[[2], [0], [1]]
[[2], [1], [0]]
[[2], [0, 1], []]
[[0, 1], [], [2]]
[[0, 1], [2], []]
[[0, 2], [], [1]]
[[0, 2], [1], []]
[[1, 2], [], [0]]
[[1, 2], [0], []]
[[0, 1, 2], [], []]

0
投票

我自己找到了一个解决方案,但我不会将其标记为已回答,看看是否存在更有效的方法。我的解决方案

set(itertools.product(set_of_classes, repeat=len(set_of_objects))

实际上它会将set set_of_classes设置为len(set_of_objects)的(笛卡尔)幂。有更好的想法吗?

© www.soinside.com 2019 - 2024. All rights reserved.