# python – Check that all rows in an array are sorted in descending order

## Question:

Check that all rows in a matrix are sorted in descending order. If they are not all in descending order, find the first row out of order and order it the same as the others.

With this code I get the rows in descending order:

``````matrix = [[-5, -6, 2], [7, 1, -3], [8, 4, -9]]

for row in matrix:
if all(x - y > 0 for x, y in zip(row[:-1], row[1:])):
print(row)
``````

That is, with the code it checks the rows ordered in descending order and prints those that are:

``````[7, 1, -3]
[8, 4, -9]
``````

It is necessary to obtain the disordered row, in this case it would be row 0, and order it the same as the others. The output should be:

``````[2, -5, -6]
[7, 1, -3]
[8, 4, -9]
``````

According to the response to Angel's comment, a couple of `list comprehensions` do the dirty work

``````matrix = [[-5, -6, 2], [7, 1, -3], [8, 4, -9]]

sted = [x for x in matrix if x == sorted(x, reverse=True)]
# Las no ordenadas están en matrix pero no en "sted"
nsted = [sorted(x, reverse=True) for x in matrix if x not in sted]

print('\n'.join(map(str, sted)))
print()
print('\n'.join(map(str, nsted)))
print('\n'.join(map(str, sted)))
``````

With the following result

``````[7, 1, -3]
[8, 4, -9]

[2, -5, -6]
[7, 1, -3]
[8, 4, -9]
``````

The original array remains unchanged and we have separate sub-arrays with the rows that were sorted and the unsorted now sorted

Scroll to Top