在 Python 中查找矩阵所有行共有的不同元素

pythonserver side programmingprogramming更新于 2025/10/10 5:00:17

假设我们有一个 m x m 阶方阵;我们必须找到给定矩阵所有行共有的所有不同元素。

因此,如果输入如下

13215417
1532436
15215412
1526432
21942215

则输出将为 [2,4,15]

为了解决这个问题,我们将遵循以下步骤 −

  • 定义一个函数 sortRows() 。这将采用矩阵

  • n := 行数

  • 对于范围从 0 到 n 的 i,执行

    • 对列表 matrix[i] 进行排序

  • 在主方法中,执行以下操作 −

  • n := 行数

  • sortRows(matrix)

  • current_idx := 大小为 n 的列表,用 0 填充

  • 对于范围从 0 到 n 的 i,执行

    • current_idx[i] := 0

  • f := 0

  • while current_idx[0] < n,执行

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

    • present := True

    • 对于范围为 1 到 n 的 i,执行

      • while (current_idx[i] < n and 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 非零,则

      • 显示值

    • 如果 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,

相关文章


有用资源