繁体   English   中英

不使用 itertools 生成重复组合

[英]Generate combinations with repetition without using itertools

我对计算机科学和算法理论的经验很少。 我需要生成并打印所有组合,并按字典顺序打印大小为 k 的数字 1..n 的重复组合。 我应该在不使用 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

样品 Output

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

请帮我找到解决方案!

递归实现:

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]

文档中,它说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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM