Enumeration of combinations of N balls in A boxes?

后端 未结 8 1014
后悔当初
后悔当初 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 19:09

    This works just fine starting with python 2.6, (2.5-friendly implementation of itertools.permutations is available as well):

    >>> import itertools
    >>> boxes = 3
    >>> balls = 8
    >>> rng = list(range(balls + 1)) * boxes
    >>> set(i for i in itertools.permutations(rng, boxes) if sum(i) == balls)
    {(0, 1, 7), (3, 1, 4), (0, 4, 4), (1, 0, 7), (4, 0, 4), (3, 0, 5), (1, 2, 5), (1, 7, 0), (0, 8, 0), (1, 4, 3), (6, 0, 2), (4, 3, 1), (3, 3, 2), (0, 5, 3), (5, 3, 0), (5, 1, 2), (2, 4, 2), (4, 4, 0), (3, 2, 3), (7, 1, 0), (5, 2, 1), (0, 6, 2), (6, 1, 1), (2, 2, 4), (1, 1, 6), (0, 2, 6), (7, 0, 1), (2, 1, 5), (0, 0, 8), (2, 0, 6), (2, 6, 0), (5, 0, 3), (2, 5, 1), (1, 6, 1), (8, 0, 0), (4, 1, 3), (6, 2, 0), (3, 5, 0), (0, 3, 5), (4, 2, 2), (1, 3, 4), (0, 7, 1), (1, 5, 2), (2, 3, 3), (3, 4, 1)}
    

提交回复
热议问题