179k views
5 votes
Write a function that takes a 2D array and first sorts the elements in each row and then sorts the rows by the first element.

Sample run:

mat = [[9, 7, 7, 0], [3, 3, 9, 8], [8, 5, 2, 9], [9, 10, 10, 9], [6, 5, 7, 4]]

my_sort(mat)

print(mat)

Prints the following:

[[0, 7, 7, 9], [2, 5, 8, 9], [3, 3, 8, 9], [4, 5, 6, 7], [9, 9, 10, 10]]

User Niqui
by
7.2k points

1 Answer

5 votes

Answer:

def my_sort(m):

for a in m:

a.sort()

m.sort(key=lambda a: a[0])

Step-by-step explanation:

The lambda tells the sort function to use the first element of the array.

User Andy Zhang
by
7.7k points