arberavdullahu arberavdullahu - 1 month ago 22
Python Question

Trying to construct identity matrix?

Write a function identity(n) that returns the n identity
matrix.

For example: identity(3) outputs [[1,0,0][0,1,0][0,0,1]]

I have tried as follow:

def identity(n):
matrix=[[0]*n]*n
i=0
while i<n:
matrix[i][i]=1
i+=1
return matrix


Also I tried with range but it did'n work like this

def identity(n):
matrix=[[0]*n]*n
k=matrix[:]
i=0
for i in range(1,n):
matrix[i][i]=1
i+=1
return k
print(identity(5))


But it output for
n = 5
:

[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

Answer

If numpy is not allowed ... Know this How to define two-dimensional array in python

and do this

def identity(n):
    m=[[0 for x in range(n)] for y in range(n)]
    for i in range(0,n):
        m[i][i] = 1
    return m