如何在Python中生成所有不同的3x3拉丁广场的列表

 收藏

拉丁广场是由n个不同符号组成的nxn数组,每个符号在每一行中出现一次,在每一列中出现一次(如数独)。拉丁广场的一个例子:

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]

The result is supposed to be like this (order doesn't matter): 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]
回复