所以基本上,我想编写一个程序来使用列表显示矩阵,并打印出矩阵是否为单位矩阵。
R = int(input('Enter no. of rows:'))
C = int(input('Enter no of columns:'))
print('Enter row wise entries:')
Mat = []
for i in range(R):
a = []
for j in range(C):
a.append(int(input()))
Mat.append(a)
for i in range(R):
for j in range(C):
print(Mat[i][j], end=' ')
print()
for i in range(R):
for j in range(C):
if i != j and Mat[i][j] != 0 or i == j and Mat[i][j] == 1:
break
print('Identity Matrix')
我能够打印出矩阵,但是不能正确地检查它的身份。请检查我的代码,然后告诉我什么地方出了错。
答案 0 :(得分:0)
您的解决方案似乎真的很接近我!
我唯一要更改的是:
R = int(input('Enter no. of rows:'))
C = int(input('Enter no of columns:'))
print('Enter row wise entries:')
Mat = []
for i in range(R):
a = []
for j in range(C):
a.append(int(input()))
Mat.append(a)
for i in range(R):
for j in range(C):
print(Mat[i][j], end=' ')
print()
isIdentity = True
if C == R: # change 1
for i in range(R):
for j in range(C):
if (i != j and Mat[i][j] != 0) or (i == j and Mat[i][j] != 1): # change 2
isIdentity = False # change 3
break
else:
isIdentity = False
if isIdentity:
print('Identity Matrix')
else:
print('Not Identity Matrix')