How to check if a given row is sorted in a matrix with Python

2 Answers

0 votes
def isRowSorted(matrix, row) :
    cols = len(matrix[0])
    i = 1
    while (i < cols) :
        if (matrix[row][i - 1] > matrix[row][i]) :
            return False
        i += 1
    return True
        
matrix = [[ 1,  2,   3,  4,  0],
          [ 5,  6, 100,  8,  2],
          [-9, -4,  -3,  2, 71],
          [ 1,  7, 100,  9,  6],
          [ 9, 10,  11, 12, 13]]
          
print("Row 0: " + str(isRowSorted(matrix, 0)))
print("Row 1: " + str(isRowSorted(matrix, 1)))
print("Row 2: " + str(isRowSorted(matrix, 2)))
print("Row 3: " + str(isRowSorted(matrix, 3)))
print("Row 4: " + str(isRowSorted(matrix, 4)))



'''
run:

Row 0: False
Row 1: False
Row 2: True
Row 3: False
Row 4: True

'''

 



answered Jun 23, 2023 by avibootz
0 votes
matrix = [[ 1,  2,   3,  4,  0],
          [ 5,  6, 100,  8,  2],
          [-9, -4,  -3,  2, 71],
          [ 1,  7, 100,  9,  6],
          [ 9, 10,  11, 12, 13]]

print("Row 0: " + str(sorted(matrix[0]) == matrix[0]))
print("Row 1: " + str(sorted(matrix[1]) == matrix[1]))
print("Row 1: " + str(sorted(matrix[2]) == matrix[2]))
print("Row 1: " + str(sorted(matrix[3]) == matrix[3]))
print("Row 1: " + str(sorted(matrix[4]) == matrix[4]))



'''
run:

Row 0: False
Row 1: False
Row 1: True
Row 1: False
Row 1: True

'''


 



answered Jun 23, 2023 by avibootz

Related questions

1 answer 128 views
2 answers 166 views
1 answer 131 views
1 answer 132 views
1 answer 147 views
...