[英]Counting symmetric matrices
I have a list of 0,1 3x3 matrices.我有一个 0,1 3x3 矩阵的列表。 I want to count how many of them are symmetrical.
我想数一数有多少是对称的。 How can I implement that?
我该如何实施? I was trying this:
我正在尝试这个:
def transpose(mat, tr, N):
for i in range(N):
for j in range(N):
tr[i][j] = mat[j][i]
l=0
def count(list):
for y in list:
tr = [ [0 for j in range(3) ] for i in range(3) ]
transpose(y, tr, 3)
if int(y[i][j]) == int(tr[i][j]):
l+= 1
But the answer is wrong.但答案是错误的。
I would just define:我只想定义:
def is_symmetric(matrix, n):
return all(matrix[i][j] == matrix[j][i] for i in range(n) for j in range(n))
The bug in your code is that you're comparing one value of y against one value of tr.您代码中的错误是您将 y 的一个值与 tr 的一个值进行比较。 You're not comparing all of them.
你不是在比较所有这些。
As an optimization, you could actually do:作为优化,您实际上可以执行以下操作:
def is_symmetric(matrix, n):
return all(matrix[i][j] == matrix[j][i]
for i, j in itertools.combinations(range(n), 2))
This eliminates looking at the diagonal and looking at each pair of elements twice.这消除了查看对角线和查看每对元素两次的情况。
First, please take a look at numpy
which can solve such a problem trivially:首先,请看一下
numpy
,它可以轻松解决这样的问题:
is_symmetric = lambda m: m.shape == m.T.shape and np.all(np.isclose(m, m.T))
But in pure Python, with a nested list of integers (for floats do not use ==
to check for equality, check abs(xy) < eps
), the following should work:但是在纯 Python 中,使用嵌套的整数列表(对于浮点数不使用
==
来检查相等性,请检查abs(xy) < eps
),以下应该有效:
def is_symmetric(m):
square = len(m) == len(m[0])
return square and all(m[i][j] == m[j][i]
for i in range(len(m))
for j in range(i+1, len(m)))
def count_symmetric(li):
return sum(is_symmetric(m) for m in li)
Your transpose function is not returning a value.您的转置函数没有返回值。 Python is not call by reference so you must return the transposed matrix.
Python 不是通过引用调用的,因此您必须返回转置矩阵。 Like so:
像这样:
def transpose(mat, N):
tr = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
tr[i][j] = mat[j][i]
return tr
Next we need to compare the matrices, we can do that simply using the ==
operator.接下来我们需要比较矩阵,我们可以简单地使用
==
运算符来完成。
>>> mat1 = [[1,0], [0,1]]
>>> mat2 = [[1,2], [3,4]]
>>> print(mat1 == transpose(mat1, 2))
True
>>> print(mat2 == transpose(mat2, 2))
False
We can then form a count function然后我们可以形成一个计数函数
def count_symetric(l):
count = 0
for mat in l:
if mat == transpose(mat, 3):
count += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.