在 Python 中檢查矩陣中第 i 行和第 i 列的和是否相同


假設我們有一個二維矩陣。我們必須檢查第 i 行的總和是否與第 i 列的總和相同。

因此,如果輸入類似於

2
3
4
5
10
6
4
2
1
4
6
7
1
5
6
7

則輸出將為 True,因為第一行和第一列的總和為 (2 + 3 + 4 + 5) = 14,而 (2 + 10 + 1 + 1) = 14。

為了解決這個問題,我們將遵循以下步驟:

  • row := mat 的行數
  • col := mat 的列數
  • total_row := 0, total_col := 0
  • 對於 i 的範圍從 0 到 row - 1,執行
    • total_row := 0, total_col := 0
    • 對於 j 的範圍從 0 到 col - 1,執行
      • total_row := total_row + mat[i, j]
      • total_col := total_col + mat[j, i]
    • 如果 total_row 與 total_col 相同,則
      • 返回 True
  • 返回 False

讓我們看看下面的實現,以便更好地理解:

示例程式碼

線上演示

def solve(mat):
   row = len(mat)
   col = len(mat[0])
   total_row = 0
   total_col = 0
   for i in range(row):
      total_row = 0
      total_col = 0
      for j in range(col):
         total_row += mat[i][j]
         total_col += mat[j][i]
       
      if total_row == total_col:
         return True
     
   return False
 
matrix = [
   [2,3,4,5],
   [10,6,4,2],
   [1,4,6,7],
    [1,5,6,7]
]
     
print(solve(matrix))

輸入

[    
[1,2,3,4],     

[9,5,3,1],     

[0,3,5,6],    

[0,4,5,6]

]

輸出

True

更新於: 2021年1月15日

197 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.