Skip to content

Commit 80022cf

Browse files
committed
added a file-transepose_of_ matirx
1 parent 2c15b8c commit 80022cf

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

matrix/transpose_of_matrix.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
""""
2+
this program returns the transpose of a given 2-D matrix
3+
The transpose of a matrix is a new matrix formed by flipping the original matrix over its diagonal.
4+
5+
In python a matrix is represented by list inside a list
6+
suppose given matrix A is
7+
[[4,5,2],
8+
A= [7,5,9],
9+
[1,8,3]]
10+
then it's transpose will be
11+
[[4,7,1],
12+
A^t = [5,5,8],
13+
[3,9,3]]
14+
15+
"""
16+
def transpose_matrix(matrix: list[list[int]]) ->list[list[int]]:
17+
"""""
18+
creating a new empty matrix for storing transposed values
19+
number of rows in the matrix=len(matrix)
20+
number of columns =number of elements in the matrix=number of element in 1st row of the matrix=len(matrix[0])
21+
"""
22+
transposed_matrix=[[0]*len(matrix) for _ in range(len(matrix[0]))]
23+
"""
24+
created an empty matrix of dimension len(matrix)*len(matrix[0])
25+
"""
26+
for i in range(len(matrix)):
27+
for j in range(len(matrix[0])):
28+
"""
29+
traversing the matrix element-by-element starting from 1st element of 1st row to last element of last row
30+
1st loop--> traversing through the row
31+
2nd loop--> traversing through the column
32+
by this whole matrix is traversing
33+
34+
"""
35+
transposed_matrix[j][i]=matrix[i][j]
36+
"""
37+
keeping the values of matrix to resultant matrix in transposed order
38+
for example 2nd element of 3rd row will be 3rd element of 2nd row
39+
1nd element of 2rd row will be 2rd element of 1nd row
40+
likwise diagonal element will reamin intact
41+
42+
"""
43+
#return the transposed_matrix
44+
return transposed_matrix
45+
"""
46+
check for main function
47+
give input and call the transpose_matrix () function with matirx as a parameter
48+
"""
49+
if __name__=="__main__":
50+
matrix=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
51+
print(transpose_matrix(matrix))
52+
53+
54+
55+

0 commit comments

Comments
 (0)