【问题标题】:Python: Finding all 6x6 matrices where each value occurs only once in each column and rowPython:查找所有 6x6 矩阵,其中每个值在每列和每行中仅出现一次
【发布时间】:2020-06-05 09:41:37
【问题描述】:

我想在 Python 中生成所有 6x6 矩阵,其中每个值(整数 1-6)在每列和每行中只出现一次(就像数独谜题,除了子网格)。我认为生成所有可能的 6x6 矩阵并在之后进行过滤不是一种选择,因为有 ~1.3*10^17 的可能性。

我发现在选择序列 1-6(总共 720 个)的排列时,矩阵的第 2 行将只有 265 种可能性,而第 3-4-5 行则更少。如果前 5 行已经被选中,第 6 行应该只有 1 种可能性。

我已经为 3x3 矩阵尝试了下面的代码并且它有效,但是我觉得添加更多具有更多比较的嵌套循环并不是解决此问题的最佳方法(如果有的话)。听起来它应该可以通过递归或列表理解来实现,但我无法确定它。

import itertools


input_list = []

for f in itertools.permutations([1,2,3],3):
  input_list.append(f)




for i in input_list:

  input_listcopy = input_list.copy()
  result = []
  result.append(i)
  input_listcopy.remove(i)

  for j in input_listcopy:
    if (i[0] != j[0] and i[1] != j[1] and i[2] != j[2]):
      result.append(j)



 print(result)

为了清楚起见,我期望的输出是一个二维列表,其中每个元素都是矩阵的一行,从顶部开始:

[[1,2,3],[2,3,1],[3,1,2]]

提前致谢!

【问题讨论】:

    标签: python matrix


    【解决方案1】:

    这个怎么样?

    from itertools import permutations
    
    # Define the permutations
    length = 6
    elements = range(1, length+1)
    
    result = []
    
    for perm in permutations(elements, length):
      if not result:  #  The first permutation is added
        result.append(perm)
        continue 
    
      is_valid_list = []
      for row in result:
        is_valid = all(perm[idx] != row[idx] for idx in range(length))
        is_valid_list.append(is_valid)
    
      if all(is_valid_list):
        result.append(perm)
    
    print(result)
    

    【讨论】:

    • 您的代码似乎只输出一种解决方案。当我以长度 3 运行它时,我希望至少有 2 个:[[1,3,2],[2,1,3],[3,2,1]][[1,2,3],[2,3,1],[3,1,2]]
    猜你喜欢
    • 2013-08-11
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多