- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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