python 通过numpy nonzero方法判断一个矩阵是否是不一致的,以下是我目前的想法,
每行最后一个不为零其它全为零则假,否则真。
import numpy as np
def judge(A):
res = np.nonzero(A)
a = map(tuple, np.transpose(res).tolist())
m,n=np.shape(A)
all_l = [(i,n -1) for i in range(m)]
for i in a:
if i not in all_l:
return True
return False
if __name__ == '__main__':
res = judge([[0,0,0], [0, 1, 2], [0, 0, 0]])
print(res)
import numpy as np
def incon(A):
m,n=np.shape(A)
if A[m-1][n-1] == 0:
for i in range(m):
for j in range(n):
if not(i == (m-1) and j == (n-1)):
if A[i][j] == 0:
print('一致')
return
else:
print('不一致')
else:
print('一致')
if __name__ == '__main__':
incon([[1,2,3], [2, 3, 5], [1, 2, 0]])
问题已解决,如有帮助还请采纳。不一致返回False,一致则返回True。
这是优化后的代码。
import numpy as np
a = np.array([[2, 3, 4], [5, 6, 1], [8, 0, 1], [2, 3, 5]])
def inconsistentSystem(A):
m, n = np.shape(A)
if len(np.nonzero(A)[0]) != m*n and A[m-1][n-1] != 0:
print("不一致")
else:
print("一致")
inconsistentSystem(a)
不一致系统的定义:一个矩阵最后一行最后一列的元素值为0,其他元素值都不为0。这样理解对吗?