Adding new file to repo

This commit is contained in:
Donald Calloway 2025-09-30 17:14:32 -07:00
parent 9f57dddd92
commit fa4c0ad98a

View File

@ -0,0 +1,48 @@
from typing import List
"""
Transposes a square matrix.
Args:
M (List[List]): A square matrix represented as a list of lists.
Returns:
List[List]: The transpose of the input square matrix.
Example:
>>> square_matrix_transpose([
... [1, 2, 3, 0],
... [4, 5, 6, 1],
... [7, 8, 9, 2],
... [1, 2, 3, 4]
... ])
[[1, 4, 7, 1], [2, 5, 8, 2], [3, 6, 9, 3], [0, 1, 2, 4]]
"""
def square_matrix_transpose(M) -> List[List]:
row = []
T = []
ncols = len(M[0]) # ncols is number of columns in matrix A
for i in range(0, ncols):
for j in range(0, ncols):
row.append(M[j][i])
T.append(row)
row = []
return T
# Example Usage
matrix = [
[1,2,3,0],
[4,5,6,1],
[7,8,9,2],
[1,2,3,4]
]
print(square_matrix_transpose(matrix))
# Output (As a matrix)
'''
[[1, 4, 7, 1],
[2, 5, 8, 2],
[3, 6, 9, 3],
[0, 1, 2, 4]]
'''