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:
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]]
)