在纯python中求行缩减梯队矩阵的所有解
我有在纯python中求行缩减梯队矩阵的所有解,python,algorithm,matrix,linear-algebra,Python,Algorithm,Matrix,Linear Algebra,我有 toggle是一个矩阵,我已经用高斯消去法转换为[行梯队形式]。这是in,这意味着-1=1和1+1=0 我已经有了一个正在工作的backSubstitute()方法: toggle = [[1, 1, 1, 1, 0, 0, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0, 1, 1,
toggle
是一个矩阵,我已经用高斯消去法转换为[行梯队形式]。这是in,这意味着-1=1
和1+1=0
我已经有了一个正在工作的backSubstitute()
方法:
toggle = [[1, 1, 1, 1, 0, 0, 1, 0, 0],
[0, 1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
puzzle = [0, 0, 0, 0, 1, 0, 0, 0, 0]
它返回一个特定的有效解决方案([0,0,1,1,1,0,0,0]
),但我知道有三种不同的解决方案:
[0,1,0,0,1,0,1,0,0]
[0,0,1,1,1,0,0,0,0]
[0,0,0,0,0,0,0,0,0,0,1]
1
s的解决方案感兴趣,因此对于本例,所需的解决方案是[0,0,0,0,0,0,1]
这需要在纯python中完成(尽管其他语言的解决方案肯定也会帮助我),而不需要第三方库,因此没有numpy或sage
对于任何对这个问题背后的基本原理感兴趣的人来说,它是一个受启发的“变量解算器”。你看过列表的
.count()
方法了吗?@user2097159当然,但是反替代()
不会返回结果列表,也不会处理结果列表,这就是问题所在。所以它听起来像反替代()
需要重新处理,因为到目前为止,它只返回1个可能的解决方案,而不是所有的解决方案?我是否遗漏了一些内容或toggle
不是真正的行梯队形式?最后一行是错误的。@user2097159是的,但我不知道我们在哪里决定一个解决方案,可以在列表中存储不同的结果。
def backSubstitute(toggle, puzzle):
# toggle (matrix) and puzzle (vector) in reduced row echelon form
# Initialize result vector
result = [0] * len(puzzle)
pivot = -1
# Iterate from the bottom up
for row in xrange(len(puzzle) - 1, -1, -1):
# Find pivot
for col in xrange(len(puzzle)):
if toggle[row][col]:
pivot = col
break
if pivot == -1:
if puzzle[row]:
raise RuntimeError("Puzzle has no solution")
else:
# iterate across the rest of the row, XORing the values
# together with the puzzle value and then store the result.
result[row] = puzzle[row]
for col in xrange(pivot + 1, len(puzzle)):
result[row] ^= toggle[row][col] and result[col]
return result