有一个由数字0-9组成的n*n矩阵.例如:
6 0 0 8 9 6 1
5 1 6 8 1 1 0
4 2 1 3 7 1 5
8 8 6 6 2 5 2
7 9 4 6 9 6 4
1 4 7 8 5 3 8
9 4 8 3 9 2 9
我需要找到要更改的最小数量的数字(在矩阵内),以使其一次关于多行(/、\、-、|)对称.
我 for each 对称(/、\、-、|)做了四个函数.他们列出了两个需要具有相同值的数字的列表.这些函数如下所示:
import math
"""lenght = how many numbers in one line"""
def symmetry_horizontaln(lenght):
for i in range(math.ceil(lenght/2)):
for j in range(lenght):
round_result = []
round_result.append((i, j))
round_result.append((lenght-i-1, j))
def symmetry_vertical(lenght):
for i in range(lenght):
for j in range(lenght):
if j < math.ceil(lenght/2):
round_result= []
round_result.append((i, j))
round_result.append((i, lenght-j-1))
def symmetry_main_diagonal(lenght):
for i in range(lenght):
for j in range(lenght):
if j <= i:
round_result= []
round_result.append((i, j))
round_result.append((j, i))
def symmetry_second_diagonal(lenght):
for i in range(lenght):
for j in range(lenght):
if j <= lenght-i-1:
round_result= []
round_result.append((i, j))
round_result.append((lenght-j-1, lenght-i-1))
现在我需要以某种方式将舍入结果放在一起,这样我就可以获得矩阵中需要具有相同值的点的列表.例如,如果有这样的矩阵:
6 0 0 8 9 6 1
5 1 6 8 1 1 0
4 2 1 3 7 1 5
8 8 6 6 2 5 2
7 9 4 6 9 6 4
1 4 7 8 5 3 8
9 4 8 3 9 2 9
它需要对这些行进行整合:-和/,最终的列表将如下所示:
[[(6, 2), (4, 0), (0, 4), (4, 6), (2, 0), (6, 4), (0, 2), (2, 6)], [(2, 3), (3, 2), (3, 4), (4, 3)], [(3, 1), (5, 3), (1, 3), (3, 5)], [(1, 2), (2, 1), (5, 4), (1, 4), (4, 5), (2, 5), (4, 1), (5, 2)], [(1, 1), (5, 5), (5, 1), (1, 5)], [(0, 1), (6, 5), (6, 1), (5, 0), (5, 6), (0, 5), (1, 0), (1, 6)], [(4, 4), (2, 4), (4, 2), (2, 2)], [(6, 3), (0, 3), (3, 6), (3, 0)], [(3, 3)], [(6, 6), (6, 0), (0, 6), (0, 0)]]
从这个列表中,我知道如何更改最小数量的数字,以使I关于这些线对称.我想现在是30岁.但我不知道怎么才能拿到那份名单.
这就是我try 过的:
我对前面的函数进行了如下修改(每个函数的最后两行都是新的):
def symmetry_horizontaln(lenght):
for i in range(math.ceil(lenght/2)):
for j in range(lenght):
round_result = []
round_result.append((i, j))
round_result.append((lenght-i-1, j))
function((i, j), round_result)
function((delka-i-1, j), round_result)
def symetry_horizontal(lenght):
...
function((i, j), round_result)
function((i, lenght-j-1), round_result)
...
并制作了一个新函数来获取最终列表:
x = []
def function(point, round_result):
if round_result[0] == round_result[1]:
round_result = list(set(round_result))
if not x:
x.append(round_result)
else:
for i in x:
if i == round_result:
pass
elif point in i:
i.append(round_result[0])
i.append(round_result[1])
else:
x.append(round_result)
break
print(x)
但这似乎行不通.如有任何帮助,我们不胜感激!