使用 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 人看過

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.