3 python combinations enumeration
我想列举A盒中N球的所有可能组合.
例如:我有8个球可以处理3个盒子:
box_1 box_2 box_3
case-1 8 0 0
case-2 0 8 0
case-3 0 0 8
case-4 7 1 0
case-5 7 0 1
case-6 6 2 0
...
Run Code Online (Sandbox Code Playgroud)
我的第一个问题是我需要A循环来执行此操作,但我希望A和N是用户的输入.那么如何在不编写用户可能需要的所有可能数量的循环的情况下做到
a和 N的值在2到800之间,因此计算时间要求很高.如何优化该算法?
如果你用python语言回答我,我将不胜感激.感谢所有的贡献!
从python 2.6开始,这很好用(2.5友好的实现itertools.permutations也是可用的):
>>> 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)}
Run Code Online (Sandbox Code Playgroud)
伪代码:
Enumerate(Balls, Boxes)
if Boxes<=0
Error
elseif Boxes=1
Box[1] = Balls
PrintBoxes
else
forall b in 0..Balls
Box[Boxes] = b
Enumerate(Balls-b, Boxes-1)
endfor
endif
end
Run Code Online (Sandbox Code Playgroud)
说明
从第一个框开始,如果没有框,则抱怨并退出.如果它是要填充的最后一个框,则丢弃所有剩余的球并显示结果.如果有更多的盒子,首先添加0个球并与其他盒子重复该过程.然后加1球2球直到没有球.
为了表明该算法有效,我给出了一个实例,3个球和2个盒子的例子.
我们有一个名为Box的盒子阵列,每个盒子可以容纳任意数量的球(值).PrintBoxes打印框的当前值.
Box = (0,0)
Enumerate(3, 2)
b=0
Box = (0,0)
Enumerate(3,1)
Box = (3,0)
Print!
b=1
Box = (0,1)
Enumerate(2,1)
Box = (2,1)
Print!
b=2
Box = (0,2)
Enumerate(1,1)
Box = (1,2)
Print!
b=3
Box = (0,3)
Enumerate(0,1)
Box = (0,3)
Print!
Output:
(3,0)
(2,1)
(1,2)
(0,3)
Which are all the combinations.
Run Code Online (Sandbox Code Playgroud)
另一个有3个盒子和3个球的例子:
Box = (0,0,0)
Enumerate(3, 3)
b=0
Box = (0,0,0)
Enumerate(3,2)
b=0
Box = (0,0,0)
Enumerate(3,1)
Box = (3,0,0)
b=1
Box = (0,1,0)
Enumerate(2,1)
Box = (2,1,0)
b=2
Box = (0,2,0)
Enumerate(1,1)
Box = (1,2,0)
b=3
Box = (0,3,0)
Enumerate(0,1)
Box = (0,3,0)
b=1
Box = (0,0,1)
Enumerate(2,2)
b=0
Box = (0,0,1)
Enumerate(2,1)
Box = (2,0,1)
b=1
Box = (0,1,1)
Enumerate(1,1)
Box = (1,1,1)
b=2
Box = (0,2,1)
Enumerate(0,1)
Box = (0,2,1)
b=2
Box = (0,0,2)
Enumerate(1,2)
b=0
Box = (0,0,2)
Enumerate(1,1)
Box = (1,0,2)
b=1
Box = (0,1,2)
Enumerate(0,1)
Box = (0,1,2)
b=3
Box = (0,0,3)
Enumerate(0,2)
b=0
Box = (0,0,3)
Enumerate(0,1)
Box = (0,0,3)
Output
(3,0,0)
(2,1,0)
(1,2,0)
(0,3,0)
(2,0,1)
(1,1,1)
(0,2,1)
(1,0,2)
(0,1,2)
(0,0,3)
Run Code Online (Sandbox Code Playgroud)