使用 Python 统计按列和按行排序的矩阵中的负数?


本例中,我们将统计按行和按列排序的矩阵中的负数。首先,我们将创建一个矩阵 -

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

将矩阵传递给自定义函数,并使用嵌套 for 循环 -

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

如上所示,for 循环中的每个矩阵元素都将检查负值。找到一个负值时,计数将增量。

以下是完整示例 -

示例

# 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

输出

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

更新日期: 12-Aug-2022

451 人看过

开启您的 职业生涯

通过完成课程获得认证

开始
广告