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

set of n objects, and show k-element subsets in python

假设你有一组 n 个对象,你想列出它的 k 个元素子集(即它的 恰好有 m 个元素的子集)由 递归函数 求解,而不使用 list(itertools.combinations) 例如 k_subsets({1,2,3},2 ) 显示

[{1, 2}, {1, 3}, {2, 3}]

这将是 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)