
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Mirror of Matrix Across Diagonal in Python
The mirror of a matrix across a diagonal means swapping the elements at position[i, j] with the elements at position[j, i].
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 is 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]]
Mirror of a Matrix Using Nested for Loop
In this approach, we will use the nested for loop to find the mirror of the matrix across a diagonal.
Example
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("Original Matrix") print(matrix) # new nested list to store mirrormatrix 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("Mirror Matrix") print(mirror_matrix)
Output
Original Matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Mirror Matrix [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Mirror of a Matrix Using List Comprehension
In this approach, we will use the concept of list comprehension to find the mirror of the matrix across a diagonal.
Example
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("Original Matrix") print(matrix) # mirror matrix using list comprehension mirror_matrix = [ [matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0])) ] print("Mirror Matrix") print(mirror_matrix)
Output
Original Matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Mirror Matrix [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Advertisements