【问题标题】:Generate combinations with repetition without using itertools在不使用 itertools 的情况下生成重复组合
【发布时间】:2020-10-09 19:09:17
【问题描述】:

我在计算机科学和算法理论方面的经验很少。我需要按字典顺序生成并打印所有重复数字 1..n 大小为 k 的组合。我应该在不使用 itertools 的情况下做到这一点。我编写了简单的代码来创建所有组合,但这还不足以解决这个任务。

 
n, k = map(int, input().split())
    def gen (n, k, prefix):
        if len(prefix) == n:
            print(*prefix)
            return
       for c in range(1, n + 1):
            if c not in prefix:
                gen(n, k, prefix +[c])
    n1 = gen(n, k, [])

示例输入

3 3

样本输出

1 1 1
1 1 2
1 1 3
1 2 2
1 2 3
1 3 3
2 2 2
2 2 3
2 3 3
3 3 3

请帮助我找到解决方案!

【问题讨论】:

  • 为什么不能使用itertools?
  • 我的任务不包括使用 itertools。我必须在没有 itertools 及其函数/方法的情况下实现递归算法。

标签: python algorithm combinations combinatorics


【解决方案1】:

递归实现:

def combrep(n, k, pos=0, start = 0, l = []):
    if pos == k:
        print(l)
    else:
        for i in range(start, n):
            combrep(n, k, pos+1, i, l + [i+1])

combrep(3,3)

[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 2, 3]
[1, 3, 3]
[2, 2, 2]
[2, 2, 3]
[2, 3, 3]
[3, 3, 3]

【讨论】:

  • hmmm...看起来很简单也很合乎逻辑,但是输出与样本不同,这是不对的。还有另外一种组合:(n + k - 1)!/k! * (n - 1)!
  • @Ignat Sonets 哎呀,我明白我误解了这个问题。请几分钟
【解决方案2】:

documentation 中,它说itertools.combinations_with_replacement 大致翻译成这个(稍作修改,所以它需要一个整数):

def combinations_with_replacement(n, r):
    pool = tuple(range(n))
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)

for i in combinations_with_replacement(3, 3):
    print(i)
for i in combinations_with_replacement(3, 3):
    print(i)
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 2, 2)
(1, 2, 3)
(1, 3, 3)
(2, 2, 2)
(2, 2, 3)
(2, 3, 3)
(3, 3, 3)

我无法想象更简单的实现。为什么不从那里开始呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多