如何解决如何在python中解决5x5矩阵中的未知数
这是一个 5x5 矩阵,所有单元格未知,它看起来像这样:
A1+B1+C1+D1+E1| 1
A2+B2+C2+D2+E2| 0
A3+B3+C3+D3+E3| 1
A4+B4+C4+D4+E4| 3
A5+B5+C5+D5+E5| 2
_______________
2 1 2 1 1
因此,可以在右侧看到行的总和,在底部可以看到列的总和。解决方案只能是 0 或 1,作为一个例子,这里是我在上面输入的特定解决方案的解决方案:
0+0+1+0+0| 1
0+0+0+0+0| 0
1+0+0+0+0| 1
1+1+0+0+1| 3
0+0+1+1+0| 2
____________
2 1 2 1 1
如您所见,将行和列相加得出右侧和底部的结果。 我的问题:您将如何使用未知数输入原始矩阵并让 python 用 0 或 1 迭代每个单元格,直到拼图完成?
解决方法
您实际上并不需要矩阵——只需使用长度为 25 的向量(元组)。它们可以根据以下方案表示 5x5 矩阵:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
这些是这些元组的索引。请注意,可以从函数 divmod
中获取索引的行和列。
您可以使用 product
中的 itertools
来迭代填充矩阵的 2**25 种可能方式。
这些想法导致了以下代码:
from itertools import product
#nxn matrices will be represented by tuples of length n**2,#in row-major order
#the following function caluculates row and column sums:
def all_sums(array,n):
row_sums = [0]*n
col_sums = [0]*n
for i,x in enumerate(array):
q,r = divmod(i,n)
row_sums[q] += x
col_sums[r] += x
return row_sums,col_sums
#in what follows,row_sums,col_sums are lists of target values
def solve_puzzle(row_sums,col_sums):
n = len(row_sums)
for p in product(range(2),repeat = n*n):
if all_sums(p,n) == (row_sums,col_sums):
return p
return "no solution"
solution = solve_puzzle([1,1,3,2],[2,2,1])
for i in range(0,25,5):
print(solution[i:i+5])
输出:
(0,1)
(0,0)
(0,0)
(1,0)
在这种情况下,蛮力是可行的。如果超出 5x5,则不再可行,并且需要更复杂的算法。
,这是 integer linear programming 问题的特例。不幸的是,0-1 整数线性规划的特殊情况仍然是 NP 完全的,尽管存在许多算法,包括启发式算法。您可以使用内置库为您执行此操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。