【问题标题】:Generate k-combinations with replacement of n-size set using maximum s-number of elements of n-size set (where s<n)使用 n 大小集合的最大 s 个元素(其中 s<n)替换 n 大小集合生成 k 组合
【发布时间】:2020-12-08 16:56:49
【问题描述】:

我知道如何使用 itertools 获得所有可能的替换组合,但我想通过使用较大集合中有限数量的元素来限制替换组合的数量。

举个例子,我有一套

[0,1,2]

我想获得带有替换的 k 组合 (k=4),但最多使用一组 [0,1,2] 中的 2 个不同元素

所以可以出现在每个组合中的元素集是:

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

在这里,我也想避免重复组合,所以在这个例子中[0,0,0,0],[1,1,1,1]或[2,2,2,2]不应该重复.

此示例的输出:

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

我希望我清楚。

【问题讨论】:

标签: python combinations itertools


【解决方案1】:

您可以尝试以下方法。

import itertools

s = [0,1,2]
k = 4
limit = 2

result = set()

for c in itertools.combinations(s, limit):
    result.update(itertools.combinations_with_replacement(c, k))

或者使用集合理解:

result = {
    r
    for c in itertools.combinations(s, 2)
    for r in itertools.combinations_with_replacement(c, k)
}

两者都导致:

print(*result, sep="\n")
(0, 0, 0, 1)
(0, 1, 1, 1)
(0, 0, 0, 0)
(0, 2, 2, 2)
(2, 2, 2, 2)
(1, 2, 2, 2)
(1, 1, 1, 2)
(1, 1, 2, 2)
(0, 0, 0, 2)
(0, 0, 1, 1)
(1, 1, 1, 1)
(0, 0, 2, 2)

【讨论】:

  • 将原始列表中的元素 2 乘以 2 只是为了举例,OP 希望对任意数量的 s 项目执行此操作,而不仅仅是 2。
  • 输出可能是您的代码第一个版本的输出,它包含重复项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-09
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多