我试图编写一个函数来创建一个独立向量列表的线性跨度,但似乎最后计算的向量会覆盖所有其他元素。如果有人可以帮我解决问题,我会很高兴。
def span_generator(liste,n):
"""function to generate the span of a list of linear independent
vectors(in liste) in the n-dimensional vectorspace of a finite
field with characteristic 2, returns a list of all elements which
lie inside the span"""
results=[]
blank=[]
for i in range(n):
blank.append(0)
a=blank
if len(liste)>1:
listenwert=liste[-1]
liste.pop(-1)
values=span_generator(liste,n)
for i in range(2):
for j in range(len(values)):
for k in range(n):
a[k]=(i*listenwert[k]+values[j][k])%2
results.append(a)
else:
for i in range(2):
for j in range(n):
a[j]=(i*liste[0][j])
results.append(a)
print(results)
return results
print(span_generator([[1,0],[0,1]],2))
给出以下结果
[[1, 0], [1, 0]]
[[1, 1], [1, 1], [1, 1], [1, 1]]
[[1, 1], [1, 1], [1, 1], [1, 1]]
而不是预期的:[[0,0],[1,0],[0,1],[1,1]]
编辑:我试图用itertools.product简化程序,但它没有解决问题。
def span_generator(liste):
n=len(liste[0])
results=[]
coeff=list(itertools.product(range(2), repeat=n))
blank=[]
for i in range(n):
blank.append(0)
for i in range(len(coeff)):
a=blank
for j in range(len(coeff[0])):
for k in range(n):
a[k]=(a[k]+coeff[i][j]*liste[j][k])%2
results.append(a)
return results
输出:span_generator([[0,1],[1,0]])
[[0, 0], [0, 0], [0, 0], [0, 0]]
但它应该给[[0,0],[0,1],[1,0],[1,1]]
另一个例子:span_generator([[0,1,1],[1,1,0]])
应该给[[0,0,0],[0,1,1],[1,1,0],[1,0,1]]
(2 = 0,因为我计算模数2)
答案 0 :(得分:1)
您可以使用itertools.product
生成系数:
n = len(liste[0])
coefficients = itertools.product(range(2), repeat=len(liste))
产生一个包含以下内容的迭代器:
[(0, 0), (0, 1), (1, 0), (1, 1)]
然后,您可以选择性地将结果与transpose
的{{1}}相乘(liste
list(zip(*liste)))
取每个维度(for coeff in coefficients:
yield [sum((a * c) for a, c in zip(transpose[i], coeff)) for i in range(n)]
)产品的总和
for i in range(n)
这会产生一个迭代器。如果您希望以列表形式显示结果,则只能在迭代器
上def span_generator3(liste):
n = len(liste[0])
transpose = list(zip(*liste))
coefficients = itertools.product(range(2), repeat=len(liste))
for coeff in coefficients:
yield [sum((a * c) for a, c in zip(transpose[i], coeff)) % 2 for i in range(n)]
list()
输出:
list(span_generator3([[1,2],[4,8]]))
[[0, 0], [4, 8], [1, 2], [5, 10]]
输出:
list(sorted(span_generator3([[1,2, 4],[8, 16, 32], [64, 128, 256]])))
如果您希望结果模2,那么只需在正确的位置添加2个字符
[[0, 0, 0],
[1, 2, 4],
[8, 16, 32],
[9, 18, 36],
[64, 128, 256],
[65, 130, 260],
[72, 144, 288],
[73, 146, 292]]
def span_generator3_mod2(liste):
n = len(liste[0])
transpose = list(zip(*liste))
coefficients = itertools.product(range(2), repeat=len(liste))
# print(list(itertools.product(range(2), repeat=len(liste))))
for coeff in coefficients:
yield [sum((a * c) for a, c in zip(transpose[i], coeff)) % 2 for i in range(n)]
给出了
list(span_generator3_mod2([[0,1,1],[1,1,0]]))