Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for Mirror of matrix across diagonal
The mirror of a matrix across a diagonal means swapping the elements at position[i, j] with the elements at position[j, i]. This operation is also known as finding the transpose of a matrix.
Problem Statement
You are given a 2-D matrix in Python in the form of a nested list, and you need to find the transpose, that is, the mirror of that matrix across the diagonal.
Example
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Method 1: Using Nested for Loop
In this approach, we will use the nested for loop to find the mirror of the matrix across a diagonal ?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original Matrix")
for row in matrix:
print(row)
# Create new nested list to store mirror matrix
mirror_matrix = [[0 for i in range(len(matrix))] for j in range(len(matrix[0]))]
# Nested for loop to iterate through lists
for i in range(len(matrix)):
for j in range(len(matrix[0])):
mirror_matrix[j][i] = matrix[i][j]
print("\nMirror Matrix")
for row in mirror_matrix:
print(row)
Original Matrix [1, 2, 3] [4, 5, 6] [7, 8, 9] Mirror Matrix [1, 4, 7] [2, 5, 8] [3, 6, 9]
Method 2: Using List Comprehension
In this approach, we will use the concept of list comprehension to find the mirror of the matrix across a diagonal ?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original Matrix")
for row in matrix:
print(row)
# Mirror matrix using list comprehension
mirror_matrix = [
[matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0]))
]
print("\nMirror Matrix")
for row in mirror_matrix:
print(row)
Original Matrix [1, 2, 3] [4, 5, 6] [7, 8, 9] Mirror Matrix [1, 4, 7] [2, 5, 8] [3, 6, 9]
Method 3: Using zip() Function
The zip() function provides the most concise way to transpose a matrix ?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original Matrix")
for row in matrix:
print(row)
# Mirror matrix using zip function
mirror_matrix = list(map(list, zip(*matrix)))
print("\nMirror Matrix")
for row in mirror_matrix:
print(row)
Original Matrix [1, 2, 3] [4, 5, 6] [7, 8, 9] Mirror Matrix [1, 4, 7] [2, 5, 8] [3, 6, 9]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Nested Loop | O(m × n) | O(m × n) | Most readable |
| List Comprehension | O(m × n) | O(m × n) | Pythonic |
| zip() Function | O(m × n) | O(m × n) | Most concise |
Conclusion
All three methods effectively transpose a matrix by swapping rows and columns. Use the nested loop approach for clarity, list comprehension for Pythonic code, or zip() for the most concise solution.
