在Python中查詢矩陣所有行共有的不同元素


假設我們有一個m x m階的方陣;我們必須找到給定矩陣所有行共有的所有不同元素。

所以,如果輸入是這樣的:

13215417
1532436
15215412
1526432
21942215

那麼輸出將是[2,4,15]

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

  • 定義一個函式sortRows()。這將接收矩陣作為引數

  • n := 行數

  • 對於i從0到n,執行:

    • 對列表matrix[i]進行排序

  • 在主方法中,執行以下操作:

  • n := 行數

  • sortRows(matrix)

  • current_idx := 一個大小為n的列表,用0填充

  • 對於i從0到n,執行:

    • current_idx[i] := 0

  • f := 0

  • 當current_idx[0] < n時,執行:

    • value := matrix[0][current_idx[0]]

    • present := True

    • 對於i從1到n,執行:

      • 當(current_idx[i] < n 且 matrix[i][current_idx[i]] <= value)時,執行:

        • current_idx[i] := current_idx[i] + 1

      • 如果matrix[i][current_idx[i] - 1]與value不同,則

        • present := False

      • 如果current_idx[i]等於n,則

        • f := 1

        • 跳出迴圈

    • 如果present為真,則

      • 顯示value

    • 如果f等於1,則

      • 跳出迴圈

    • current_idx[0] := current_idx[0] + 1

示例

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

 線上演示

MAX = 100
def sortRows(matrix):
   n = len(matrix)
   for i in range(0, n):
      matrix[i].sort();
def find_common(matrix):
   n = len(matrix)
   sortRows(matrix)
   current_idx = [0] * n
   for i in range (0, n):
      current_idx[i] = 0
   f = 0
   while(current_idx[0] < n):
      value = matrix[0][current_idx[0]]
      present = True
      for i in range (1, n):
         while (current_idx[i] < n and matrix[i][current_idx[i]] <= value):
            current_idx[i] = current_idx[i] + 1
         if (matrix[i][current_idx[i] - 1] != value):
            present = False
         if (current_idx[i] == n):
            f = 1
            break
      if (present):
         print(value, end = ", ")
      if (f == 1):
         break
      current_idx[0] = current_idx[0] + 1

mat = [
   [13, 2, 15, 4, 17],
   [15, 3, 2, 4, 36],
   [15, 2, 15, 4, 12],
   [15, 26, 4, 3, 2],
   [2, 19, 4, 22, 15]]
find_common(mat)

輸入

[[13, 2, 15, 4, 17],
[15, 3, 2, 4, 36],
[15, 2, 15, 4, 12],
[15, 26, 4, 3, 2],
[2, 19, 4, 22, 15]]

輸出

2, 4, 15,

更新於:2020年8月25日

201 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告