python - 用 m 种颜色给 n 个盒子着色

标签 python numpy python-itertools

我有 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/

相关文章:

python - 尝试使用 django 美味馅饼发布时出现 404 错误

python - 测试没有重复元素的列表

python - 为什么决定系数 R² 的实现会产生不同的结果?

python - Numpy.copy 无法按预期进行随机采样

python 使用 pool.map_async 时没有输出

python 长度为 k 的 0,1 的所有可能组合

python - "Regrouping"来自嵌套字典的数据

python - 将日期时间导入 pandas DataFrame 会引发 OutOfBoundsDatetime 错误

python-如何爬过__VIEWSTATE

python - numpy.extract 和 numpy.any 函数,是否可以使其更简单?