Skip to content

Commit 1a56cb0

Browse files
committed
transpose matrix
1 parent 778a457 commit 1a56cb0

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

DataStructures/TransposeMatrix.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def transpose_matrix(matrix):
2+
# Check if the matrix is empty
3+
if not matrix or not matrix[0]:
4+
return []
5+
6+
# Use list comprehension to transpose the matrix
7+
transposed = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
8+
return transposed
9+
10+
# Example usage
11+
matrix = [
12+
[1, 2, 3],
13+
[4, 5, 6],
14+
[7, 8, 9]
15+
]
16+
17+
transposed_matrix = transpose_matrix(matrix)
18+
print(transposed_matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

0 commit comments

Comments
 (0)