48 lines
975 B
Python
48 lines
975 B
Python
|
|
|
|
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]]
|
|
|
|
''' |