我正在尝试解决XOR方程系统。例如:
A = [[1, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 1], [0, 1, 1, 0, 1], [0, 1, 0, 1, 1]]
s = [3, 14, 13, 5, 2]
m = 5 # len(s)
Ax = s => x = [12, 9, 6, 1, 10]
我试过两种方法:
你能告诉我有没有办法或python库来加快速度。即使我试图使用gmpy2库,但它不能减少太多。下面我描述了python代码,以便您可以轻松地遵循。
使用高斯消元:
def SolveLinearSystem (A, B, N):
for K in range (0, N):
if (A[K][K] == 0):
for i in range (K+1, N):
if (A[i][K]!=0):
for L in range (0, N):
s = A[K][L]
A[K][L] = A[i][L]
A[i][L] = s
s = B[i]
B[i] = B[K]
B[K] = s
break
for I in range (0, N):
if (I!=K):
if (A[I][K]):
#M = 0
for M in range (K, N):
A[I][M] = A[I][M] ^ A[K][M]
B[I] = B[I] ^ B[K]
SolveLinearSystem (A, s, 5)
使用反转
def identitymatrix(n):
return [[long(x == y) for x in range(0, n)] for y in range(0, n)]
def multiply_vector_scalar (vector, scalar, q):
kq = []
for i in range (0, len(vector)):
kq.append (vector[i] * scalar %q)
return kq
def minus_vector_scalar(vector1, scalar, vector2, q):
kq = []
for i in range (0, len(vector1)):
kq.append ((vector1[i] - scalar * vector2[i]) %q)
return kq
def inversematrix(matrix, q):
n = len(matrix)
A =[]
for j in range (0, n):
temp = []
for i in range (0, n):
temp.append (matrix[j][i])
A.append(temp)
Ainv = identitymatrix(n)
for i in range(0, n):
factor = gmpy2.invert(A[i][i], q) #invert mod q
A[i] = multiply_vector_scalar(A[i],factor,q)
Ainv[i] = multiply_vector_scalar(Ainv[i],factor,q)
for j in range(0, n):
if (i != j):
factor = A[j][i]
A[j] = minus_vector_scalar(A[j], factor, A[i], q)
Ainv[j] = minus_vector_scalar(Ainv[j], factor, Ainv[i], q)
return Ainv
def solve_equation (A, y):
result = []
for i in range (0, m):
temp = 0
for j in range (0, m):
temp = (temp ^ A[i][j]* y[j])
result.append(temp)
return result
A_invert = inversematrix(A, 2)
print solve_equation (A_invert, s)
答案 0 :(得分:0)
您提供的两种方法都可以进行立方数的位操作。有些方法更快,无论是渐近还是在实践中。
第一步(对你来说可能已足够)是使用32位整数(我相信它们在Python中称为numpy.int32
)来存储一行的32个连续元素。在足够大的输入上,这将使行减少速度接近32,并且可能会显着影响您在适度输入上的运行时间。
在您的特定代码中,您可以轻松地专注于mod-2案例。在代码中搜索%
和inversemodp
并处理所有这些内容;额外的,毫无意义的操作肯定无法帮助你的运行时。