Added matrix_transpose.py

This commit is contained in:
Donald Calloway 2025-09-30 17:49:44 -07:00
parent fa4c0ad98a
commit 2410ae43f4

41
matrix_transpose.py Normal file
View File

@ -0,0 +1,41 @@
from typing import List
"""
Transpose a given matrix.
Args:
M (List[List]): A 2D list representing the matrix to be transposed.
Returns:
List[List]: The transposed matrix.
Example:
>>> matrix = [
... [1, 2, 3],
... [4, 5, 6]
... ]
>>> matrix_transpose(matrix)
[[1, 4], [2, 5], [3, 6]]
"""
def matrix_transpose(M) -> List[List]:
row = []
T = []
mcols = len(M[0])
nrows = len(M)
for i in range(0, mcols):
for j in range(0, nrows):
row.append(M[j][i])
T.append(row)
row = []
return T
matrix = [
[1,2,3,0],
[4,5,6,1],
[7,8,9,2],
[1,2,3,4],
[4,5,6,7]
]
print(matrix_transpose(matrix))
# Output
# [[1, 4, 7, 1, 4], [2, 5, 8, 2, 5], [3, 6, 9, 3, 6], [0, 1, 2, 4, 7]]