- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Sort the matrix row-wise and column-wise using Python
- How to search in a row wise and column wise increased matrix using C#?
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Row-wise vs column-wise traversal of matrix in C++
- Find median in row wise sorted matrix in C++
- How can a specific operation be applied row wise or column wise in Pandas Python?
- How to search in a row wise increased matrix using C#?
- Find a common element in all rows of a given row-wise sorted matrix in C++
- C++ program to remove row or column wise duplicates from matrix of characters
- Python – Element wise Matrix Difference
- How to find the row-wise mode of a matrix in R?
- Row-wise common elements in two diagonals of a square matrix in C++
- Display the Numerical positive and negative element-wise in Numpy
- How to find the row-wise index of non-NA values in a matrix in R?
- Stack arrays in sequence vertically (row wise) in Numpy

Advertisements