Enumeration of combinations of N balls in A boxes?

后端 未结 8 1041
后悔当初
后悔当初 2020-12-30 18:06

I want to enumerate all possible combinations of N balls in A boxes.

example: I have 8

8条回答
  •  再見小時候
    2020-12-30 18:47

    See itertools.combinations_with_replacement in 3.1 for an example written in python. Additionally, it's common in combinatorics to transform a combination-with-replacement problem into the usual combination-without-replacement problem, which is already builtin in 2.6 itertools. This has the advantage of not generating discarded tuples, like solutions based on product or permutation. Here's an example using the standard (n, r) terminology, which would be (A, N) in your example.

    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)]
    

提交回复
热议问题