【问题标题】:set of n objects, and show k-element subsets in pythonn 个对象的集合,并在 python 中显示 k 元素子集
【发布时间】:2020-06-02 15:09:58
【问题描述】:

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

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

【问题讨论】:

  • 你的意思是正好有 k 个元素的子集吗?
  • 你能证明自己任何努力解决这个问题吗?
  • 是的,正好有 k 个元素的子集 Finn
  • 我知道算法,算法组合输入 S,一组 n 个对象 m,您想从 S 中挑选的对象数量,m n 输出大小为 n 的 S 的子集jSj = m 让结果 = fSg 否则让结果 = ;对于 s 2 S 让 U = Sns 添加组合(U,m)到结果返回结果 Scott Hunter
  • 您的问题到底是什么?后半部分好像忘记写了。你的第一句话以“假设你想做这做那”开头,但随后就停止了。

标签: python subset element sage


【解决方案1】:

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

【讨论】:

  • 很好,答案是正确的,但不是我问题的确切答案。我想要只出现这些 '[{1, 2}, {1, 3}, {2, 3}]' 的代码,而不是全部。仅仅因为我们使用子集而不是有序对。例如 [{1,1}] 是不可接受的,因为我们使用了 1 一次或 {1,2} 和 {2,1} 相同。
  • @AminAmin 现在检查我是否已更新我的答案。这是根据你的意愿。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多