- Related Questions & Answers
- Average numbers in array in C Programming
- C Program to Multiply two Floating Point Numbers?
- Sum of the numbers up to N that are divisible by 2 or 5 in c programming
- Sum of first n natural numbers in C Program
- HTML DOM console.count() Method
- C/C++ Programming to Count trailing zeroes in factorial of a number?
- Sum of squares of first n natural numbers in C Program?
- Sum of squares of the first n even numbers in C Program
- To count Vowels in a string using Pointer in C++ Program
- 10 Interesting Python Cool Tricks
- howdoi in Python
- How to print without newline in Python?
- How to download Google Images using Python
- How to clear screen in python?
- get() method for dictionaries in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this section we are going to see a python program that counts negative numbers in Row-wise and Column-wise sorted matrix with optimal solution.

Row-wise and column-wise sorted array means, each value at any index is small or equal to the value at the index in next column and next row.

M = [[-40, -12, 1, 5], [-20, -2, 5, 15], [-22, -1, 13, 18], [-12, 0, 15, 38]]

In above matrix M, the first column of first row is -40, which is smaller than the value at next column value in same row i.e. -12 and is also smaller than the value in next row in the same column i.e. -20 and so on.

# The matrix must be sorted in ascending order. If not, the algorithm will not work properly matrix = [ [-40, -12, 1, 5], [-20, -2, 5, 15], [-22, -1, 13, 18], [-12, 0, 15, 38]] # To obtain the number of row rowCount = len(matrix) columnCount = 0 # To obtain the number of column for i in matrix[0]: columnCount += 1 a = 0 b = 0 count_Of_Negative_Integer = 0 while a < rowCount and b < columnCount: if matrix[a][b] >= 0: a += 1 b = 0 else: count_Of_Negative_Integer += 1 b += 1 print("Count of Negative Integers in sorted Matrix is: ",count_Of_Negative_Integer)

Count of Negative Integers in sorted Matrix is: 7

In above program,

>=0: first we try to find the count of negative integer, less than 0.

Because in above program, we are trying to get negative integers, however, same program can be used to find the count of integer that is less than any particular integers(n). For example to find the count of integer that is less than or equal to 5 using >5.

Advertisements