Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting matrix columns

I have a matrix 4*5 and I need to sort it by several columns. Please help me figure out why the answer does not match.

I spent a lot of hours and maybe a stupid mistake. I would be grateful if you could point it out to me.

sort_columns = [3, 1, 2, 4, 5, 2]
matrix = [[3, 1, 8, 1, 9],
          [3, 7, 8, 2, 9],
          [2, 7, 7, 1, 2],
          [2, 1, 7, 1, 9]]
sort_matrix_columns(matrix, len(matrix), sort_columns)
def sort_matrix_columns(matrix, n, sort_columns):
    for col in sort_columns:
        column = col - 1
        for i in range(n):
            for j in range(i + 1, n):
                if matrix[i][column] > matrix[j][column]:
                    temp = matrix[i]
                    matrix[i] = matrix[j]
                    matrix[j] = temp

I expect to get the result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2 1 7 1 9
3 1 8 1 9
2 7 7 1 2
3 7 8 2 9

But I get the following:

3 1 8 1 9 
2 1 7 1 9 
2 7 7 1 2 
3 7 8 2 9 

>Solution :

You can just use the default sorted() function, and give it a key to retrieve the column values, at which point the rows are sorted by comparing the key values directly.

The key is callable (like a function) that is given each item that’s being sorted, and you need to return a value that’s being compared.

In your case, just map the column numbers, in reverse:

def sort_matrix_columns(matrix, sort_columns):
    return sorted(
        matrix,
        key=lambda row: [row[col - 1] for col in sort_columns[::-1]]
    )

Note that the n argument to the function can be dropped, it is not used.

Demo:

>>> sort_columns = [3, 1, 2, 4, 5, 2]
>>> matrix = [[3, 1, 8, 1, 9],
...           [3, 7, 8, 2, 9],
...           [2, 7, 7, 1, 2],
...           [2, 1, 7, 1, 9]]
>>> sorted(matrix, key=lambda row: [row[col - 1] for col in sort_columns[::-1]])
[[2, 1, 7, 1, 9], [3, 1, 8, 1, 9], [2, 7, 7, 1, 2], [3, 7, 8, 2, 9]]

The code returns a new, sorted list. If you must sort your matrix in-place, use list.sort():

def sort_matrix_columns(matrix, sort_columns):
    matrix.sort(
        key=lambda row: [row[col - 1] for col in sort_columns[::-1]]
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading