Suppose we have a (n by n) matrix M, we have to find its transpose. As we know the transpose of a matrix switches the row and column indices. More formally, for every r and c, matrix[r][c] = matrix[c][r].
So, if the input is like
7 | 2 | 6 |
3 | 7 | 2 |
5 | 3 | 7 |
then the output will be
7 | 3 | 5 |
2 | 7 | 3 |
6 | 2 | 7 |
To solve this, we will follow these steps −
- M := a new list
- tracker := 0
- while tracker < row count of matrix, do
- temp := a new list
- for each row in matrix, do
- temp := join temp and a list with element row[tracker]
- M := M join another list with element temp
- tracker := tracker + 1
- return M
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): M = [] tracker = 0 while tracker < len(matrix): temp = [] for row in matrix: temp += [row[tracker]] M += [temp] tracker += 1 return M ob = Solution() matrix = [ [7, 2, 6], [3, 7, 2], [5, 3, 7] ] print(ob.solve(matrix))
Input
[[7, 2, 6], [3, 7, 2], [5, 3, 7]]
Output
[[7, 3, 5], [2, 7, 3],[6, 2, 7]]