Adding new file to repo
This commit is contained in:
parent
9f57dddd92
commit
fa4c0ad98a
48
square_matrix_transpose.py
Normal file
48
square_matrix_transpose.py
Normal 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]]
|
||||||
|
|
||||||
|
'''
|
||||||
Loading…
Reference in New Issue
Block a user