Python practice problem

 

Given a matrix M write a function Transpose which accepts a matrix M and return the transpose of M.

Transpose of a matrix is a matrix in which each row is changed to a column or vice versa.

Input 
A matrix M
[[1,2,3],[4,5,6],[7,8,9]]

Output
Transpose of M
[[1,4,7],[2,5,8],[3,6,9]]

SOLUTION:

#Transverse of a matrix

#Creating a function trans that will return the transpose of the matrix when the given matrix is passed as an argument
def trans(M,n):
    
    '''
    M=Matrix
    n=order of the matrix
    '''
    
    Trans_mat=[] #Creating a new matrix in which we will be storing the transpose of the matrix value
    #Creating the trans_mat a null matrix so that we can replace the values and put the transposed values in there
    
    for i in range(n):
        l=[]
        for j in range(n):
            l.append("0")
        Trans_mat.append(l)
        
    
    for i in range(n):
        for j in range(n):
            Trans_mat[i][j] = M[j][i]
            
    return Trans_mat


a=[]
n=int(input("Enter the order of the matrix"))
for i in range(n):
    l=[]
    for j in range(n):
        val=int(input())
        l.append(val)
    a.append(l)
    
ans=trans(a, n) 
for i in range(n):
    for j in range(n):
        print(ans[i][j],end=" ")
    print()

Comments

Popular Posts