Ordered Matrix
Given a M x N matrix, write a program to print the matrix after ordering all the elements of the matrix in increasing order.Input
The first line of input will contain two space-separated integers, denoting the M and N.
The next M following lines will contain N space-separated integers, denoting the elements of each list.
input:
3 3
1 20 3
30 10 2
5 11 15
output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
M=int(input())
ValueError: invalid literal for int() with base 10: '3 3'
expected output:
1 2 3
5 10 11
15 20 30
input:
2 5
-50 20 3 25 -20
88 17 38 72 -10
expected output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
M=int(input())
ValueError: invalid literal for int() with base 10: '2 5'
please rectify it:
def sort_matrix(matrix, M, N):
all_values = []
for row in matrix:
for element in row:
all_values.append(element)
all_values.sort(reverse=True)
sorted_matrix = []
for i in range(M):
sorted_matrix.append([])
for j in range(N):
sorted_matrix[i].append(all_values.pop())
return sorted_matrix
M, N = [int(x) for x in input().split()]
input_matrix = []
for i in range(M):
row = [int(x) for x in input().split()]
input_matrix.append(row)
answer = sort_matrix(input_matrix, M, N)
answer_string = ''
for row in answer:
answer_string += ' '.join([str(x) for x in row]) + '\n'
print(answer_string)
Comments
Leave a comment