身份或非身份矩阵

时间:2019-09-15 16:20:09

标签: python

所以基本上,我想编写一个程序来使用列表显示矩阵,并打印出矩阵是否为单位矩阵。

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')

我能够打印出矩阵,但是不能正确地检查它的身份。请检查我的代码,然后告诉我什么地方出了错。

1 个答案:

答案 0 :(得分:0)

您的解决方案似乎真的很接近我!

我唯一要更改的是:

  • 检查列数==行数
  • 在if语句的第二部分中,检查每个元素是否检查i == j和Mat [i] [j] == 1,但对于不为恒等式的矩阵的正确检查应为Mat [i] [j]!= 1
  • 添加一个标志,以在您进行的检查中跟踪矩阵是否为同一身份
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')