n个对象的集合,并在python中显示k个元素子集。

问题描述 投票:0回答:1

假设你有一个n个对象的集合,你想列出它的k个元素子集(也就是它的子集正好有m个元素),解为 递归函数 而不使用 list(itertools.combinations)比如 k_subsets({1,2,3},2 ) 显示

[{1, 2}, {1, 3}, {2, 3}]
python subset element sage
1个回答
0
投票

这将是以下代码 combination 使用递归,这将给你所有给定列表的子集和所需长度的子集。

l1 = [1, 2, 3]
s = 2
unique = []
def combination(set):
    if set == []:
        return [[]]

    sub = combination(set[1:])
    # This will give you all the subsets of given list and This is also the return variable of the function.
    all_combination = (sub + [[set[0]] + x for x in sub])
    ########################################################
    # This for loop will give you a subsets of desire length.
    for i in range(len(all_combination)):
        if int(len(all_combination[i])) == s and all_combination[i] not in unique:
            unique.append(all_combination[i])
    #########################################################
    return all_combination

print(combination(l1))
print(unique)

Output

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