 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Column Sort of a Matrix in Python
Suppose we have a matrix, we have to sort each of the columns in ascending order.
So, if the input is like
| 11 | 21 | 31 | 
| 6 | 6 | 4 | 
| 1 | 11 | 8 | 
then the output will be
| 1 | 6 | 4 | 
| 6 | 11 | 8 | 
| 11 | 21 | 31 | 
To solve this, we will follow these steps −
- R := row count of matrix, C := column count of matrix
- res := matrix of same size as given matrix and fill with 0
- for col in range 0 to C, do- values := take the elements as a vector of matrix[col]
- for row in range 0 to R, do- res[row, col] := delete last element from values
 
 
- return res
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): R = len(matrix) C = len(matrix[0]) res = [[0] * C for _ in range(R)] for col in range(C): values = [r[col] for r in matrix] values.sort(reverse=True) for row in range(R): res[row][col] = values.pop() return res ob = Solution() matrix = [[11, 21, 31],[6, 6, 4],[1, 11, 8]] print(ob.solve(matrix))
Input
[[11, 21, 31], [6, 6, 4], [1, 11, 8]]
Output
[[1, 6, 4],[6, 11, 8],[11, 21, 31]]
Advertisements
 