我有 n 个盒子,我想用 m 种颜色给它们上色。我想允许颜色重复。例如给定 4 个盒子和两种颜色。用 1 和 2 表示颜色,我们有以下方法来给它们着色
[[1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 2, 1], [1, 1, 2, 2], [1, 2, 1, 1],
[1, 2, 1, 2], [1, 2, 2, 1], [1, 2, 2, 2], [2, 1, 1, 1], [2, 1, 1, 2],
[2, 1, 2, 1], [2, 1, 2, 2], [2, 2, 1, 1], [2, 2, 1, 2], [2, 2, 2, 1],
[2, 2, 2, 2]]
其中,例如 [1,1,1,1] 表示使用第一种颜色为框 1 着色,使用第一种颜色为框 2 着色,直到最后一个框。而 [1, 1, 2, 1] 表示用颜色 1 对框 1,2 和 4 着色,对框 3 用颜色 2 着色。
为此我定义了以下函数
def recursive_fun(number_of_boxes,number_of_colors):
possible_colors=range(1,number_of_colors+1)
if number_of_boxes==1:
return [[i] for i in possible_colors]
else:
output=[]
y=recursive_fun(number_of_boxes-1,number_of_colors)
for i in y:
for m in possible_colors:
output.append(i+[m])
return output
该功能正在运行,但我希望有一种更有效的方法来执行此操作。有没有办法使用 itertools 包来做到这一点?
最佳答案
你的意思是像itertools.product
?
import itertools
colours = (1, 2)
for x in itertools.product(colours, repeat=4):
print(x)
打印:
(1, 1, 1, 1)
(1, 1, 1, 2)
(1, 1, 2, 1)
(1, 1, 2, 2)
(1, 2, 1, 1)
(1, 2, 1, 2)
(1, 2, 2, 1)
(1, 2, 2, 2)
(2, 1, 1, 1)
(2, 1, 1, 2)
(2, 1, 2, 1)
(2, 1, 2, 2)
(2, 2, 1, 1)
(2, 2, 1, 2)
(2, 2, 2, 1)
(2, 2, 2, 2)
关于python - 用 m 种颜色给 n 个盒子着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221933/