请参考Python 3.1中的itertools.combinations_with_replacement进行示例编写。此外,在组合数学中,通常将带替换的组合问题转化为不带替换的组合问题,这在2.6的itertools中已经内置。这种方法的优点是不会生成像基于product或permutation的解决方案中那样的被丢弃的元组。以下是使用标准(n,r)术语的示例,这将在您的示例中表示为(A,N)。
import itertools, operator
def combinations_with_replacement_counts(n, r):
size = n + r - 1
for indices in itertools.combinations(range(size), n-1):
starts = [0] + [index+1 for index in indices]
stops = indices + (size,)
yield tuple(map(operator.sub, stops, starts))
>>> list(combinations_with_replacement_counts(3, 8))
[(0, 0, 8), (0, 1, 7), (0, 2, 6), (0, 3, 5), (0, 4, 4), (0, 5, 3), (0, 6, 2), (0, 7, 1), (0, 8, 0), (1, 0, 7), (1, 1, 6), (1, 2, 5), (1, 3, 4), (1, 4, 3), (1, 5, 2), (1, 6, 1), (1, 7, 0), (2, 0, 6), (2, 1, 5), (2, 2, 4), (2, 3, 3), (2, 4, 2), (2, 5, 1), (2, 6, 0), (3, 0, 5), (3, 1, 4), (3, 2, 3), (3, 3, 2), (3, 4, 1), (3, 5, 0), (4, 0, 4), (4, 1, 3), (4, 2, 2), (4, 3, 1), (4, 4, 0), (5, 0, 3), (5, 1, 2), (5, 2, 1), (5, 3, 0), (6, 0, 2), (6, 1, 1), (6, 2, 0), (7, 0, 1), (7, 1, 0), (8, 0, 0)]
set(i for i in itertools.permutations(rng+rng, boxes) if sum(i) == balls)AttributeError:“module”对象没有“permutations”属性。 - solrng应该使用迭代器定义——rng = itertools.chain(*[xrange(balls + 1)] * balls)。 - Ben Blank