Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix using Python?



In this example, we will count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix. At first, we will create a matrix −

mat = [
   [-1, 3, 5, 7],
   [-6, -3, 1, 4],
   [-5, -1, -10, 12]
]

Pass the matrix to a custom function and use nested for loop −

def negativeFunc(mat, r, c):
   count = 0
      for i in range(r):
         for j in range(c):
            if mat[i][j] < 0:
	       count += 1
	    else:
	   break
return count

Above, in the for loop each matrix element is checked for negative values. On finding a negative value, the count increments.

Here’s the complete example −

Example

# The matrix must be sorted in ascending order, else it won't work def negativeFunc(mat, r, c): count = 0 for i in range(r): for j in range(c): if mat[i][j] < 0: count += 1 else: break return count # Driver code mat = [ [-1, 3, 5, 7], [-6, -3, 1, 4], [-5, -1, -10, 12] ] print("Matrix = ",mat) print("Count of Negative Numbers = ",negativeFunc(mat, 3, 4))
Matrix = [[-1, 3, 5, 7], [-6, -3, 1, 4], [-5, -1, -10, 12]] Count of Negative Numbers = 6

Output

Matrix =  [[-1, 3, 5, 7], [-6, -3, 1, 4], [-5, -1, -10, 12]]
Count of Negative Numbers =  6

Advertisements