【问题标题】:How to generate a list of all distinct 3x3 Latin Square in Python如何在 Python 中生成所有不同的 3x3 拉丁方的列表
【发布时间】:2020-03-27 04:53:57
【问题描述】:

Latin Square 是一个 nxn 数组,其中包含 n 个不同的符号,每个符号在每一行中恰好出现一次,在每列中恰好出现一次(如数独)。拉丁方的一个例子:

1 2 3
2 3 1
3 1 2

这是我尝试过的,但仍然不是完全不同

grid = []
temp = []
block = [[1,2,3],
         [2,3,1],
         [3,1,2]]
perm = permutations(block)
for i in perm:  #row permutations
    temp.extend(i)
    if len(temp)==3:
        grid.extend([temp])
        temp = []
for perm in zip(permutations(block[0]), permutations(block[1]), permutations(block[2])): #column permutations
    temp.extend([perm])
for i in range(len(temp)):  #convert to list
    temp[i] = list(temp[i])
    for j in range(len(temp[0])):
        temp[i][j] = list(temp[i][j])
grid.extend(temp)
for i in grid:
    for j in i:
        print(j)
    print()

输出是:

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

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

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

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

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

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

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

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

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

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

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

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

结果应该是这样的(顺序无所谓):Latin Square

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

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

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

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

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

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

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

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

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

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

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

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

【问题讨论】:

  • 您也可以将每个结果转换为元组的元组,使其可散列,然后将其添加到集合中,最后输出集合。
  • 哦,看起来不错!我对C还不是很熟悉,试试看。顺便说一句,谢谢。

标签: python combinatorics sudoku latin-square


【解决方案1】:

您可以将递归与生成器一起使用:

def row(n, r, c = []):
   if len(c) == n:
      yield c
   for i in range(1, n+1):
      if i not in c and i not in r[len(c)]:
         yield from row(n, r, c+[i])

def to_latin(n, c = []):
  if len(c) == n:
     yield c
  else:
     for i in row(n, [[]]*n if not c else list(zip(*c))):
        yield from to_latin(n, c+[i])

for i in to_latin(3):
  for b in i:
    print(b)
  print('-'*9)

输出:

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

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 2011-07-15
    • 1970-01-01
    • 2011-01-30
    • 2016-06-04
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    相关资源
    最近更新 更多