主要的问题是,我必须安排矩阵:

matrix1 = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])
matrix2 = np.array([[0, 0, 1], [0, 0, 0], [1, 0, 0]])
matrix3 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])
matrix4 = np.array([[1, 0, 1], [0, 0, 0], [1, 0, 1]])
matrix5 = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
matrix6 = np.array([[1, 1, 1], [0, 0, 0], [1, 1, 1]])
matrix7 = np.array([[1, 1, 1], [1, 0, 0], [1, 1, 1]])
matrix8 = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]])
matrix9 = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])

转换成一个9x9矩阵,

row_sums == [9, 4, 9, 5, 2, 5, 4, 3, 4]) and
column_sums == [5, 4, 5, 7, 4, 7, 5, 4, 4]) and
diagonal_sum1 == 6 and diagonal_sum2 == 6)

所有矩阵必须使用,并且只能使用一次,并且不能旋转.

visual

在纸上我知道它应该是什么,但不能使工作在Python.

我试着用蛮力,随机放置它们,直到它找到正确的解决方案(用IF判断和),但程序只是被冻结了.

试图安排他们的地方1,2,3和判断,但不知道如何不使用什么是使用的,轮胎新的,并在下一节使用失败之前.

有没有办法在Python中解决这个问题?

推荐答案

蛮力版本(没有任何优化):

from itertools import permutations

import numpy as np

matrices = [
    matrix1,
    matrix2,
    matrix3,
    matrix4,
    matrix5,
    matrix6,
    matrix7,
    matrix8,
    matrix9,
]

for c in permutations(matrices, 9):
    r1 = np.r_[c[0], c[1], c[2]]
    r2 = np.r_[c[3], c[4], c[5]]
    r3 = np.r_[c[6], c[7], c[8]]

    f = np.c_[r1, r2, r3]

    row_sums = f.sum(axis=1)
    if np.allclose(row_sums, [9, 4, 9, 5, 2, 5, 4, 3, 4]):
        col_sums = f.sum(axis=0)
        if np.allclose(col_sums, [5, 4, 5, 7, 4, 7, 5, 4, 4]):
            if f.diagonal().sum() == 6 and np.fliplr(f).diagonal().sum() == 6:
                print("Solution:")
                print(f)
                break

打印(在AMD 5700x上需要大约13秒):

Solution:
[[1 1 1 1 1 1 1 1 1]
 [1 1 1 0 0 0 1 0 0]
 [1 1 1 1 1 1 1 1 1]
 [0 0 1 1 0 1 1 0 1]
 [0 1 0 0 0 0 0 1 0]
 [1 0 0 1 0 1 1 0 1]
 [0 0 1 1 1 1 0 0 0]
 [0 0 0 1 0 1 0 1 0]
 [1 0 0 1 1 1 0 0 0]]

real    0m13,802s
user    0m0,008s
sys     0m0,008s

Python相关问答推荐

如何使用Jinja语法在HTML中重定向期间传递变量?

海运图:调整行和列标签

聚合具有重复元素的Python字典列表,并添加具有重复元素数量的新键

如何更改分组条形图中条形图的 colored颜色 ?

在极性中创建条件累积和

计算分布的标准差

Pandas GroupBy可以分成两个盒子吗?

如何在BeautifulSoup/CSS Select 器中处理regex?

Python Pandas—时间序列—时间戳缺失时间精确在00:00

为什么'if x is None:pass'比'x is None'单独使用更快?

Odoo16:模板中使用的docs变量在哪里定义?

为用户输入的整数查找根/幂整数对的Python练习

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

Python OPCUA,modbus通信代码运行3小时后出现RuntimeError

无法在盐流道中获得柱子

如何在Pandas中用迭代器求一个序列的平均值?

遍历列表列表,然后创建数据帧

如何获取给定列中包含特定值的行号?

普洛特利express 发布的人口普查数据失败

具有不同坐标的tkinter canvs.cocords()和canvs.moveto()