heapq in Python to print all elements in sorted order from a row and column sorted matrix

Arrays | File handling | Python Methods and Functions | String Variables

Examples:

 Input: mat = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output: Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] 

This problem has an existing solution, please refer to combining two sorted arrays using heapq module .

# A function to print all elements in sorted order
# from a matrix sorted by row and column

from heapq import merge

 

def sortedMatrix (mat ):

 

# initialize the result variable with the first line matrices

result = mat [ 0 ]

 

# now go through the full matrix

# after the first row and concatenate each row with

# result one by one

# after the last operation, the result will contain

# list of sorted matrix elements

for row in mat [ 1 :]:

  result = list (merge (result, row))

  

  return result

  

if __ name__ = = "__ main__" :

  mat = [[ 10 , 20 , 30 , 40 ], [ 15 , 25 , 35 , 45 ],

[ 27 , 29 , 37 , 48 ], [ 32 , 33 , 39 , 50 ]]

  print 'Elements of matrix in sorted order'

  print sortedMatrix (mat)

Output:

 Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] 

This article courtesy of Shashankom Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials