在Python中查找矩阵所有行共有的不同元素
假设我们有一个mxm阶的方阵;我们必须找到给定矩阵所有行共有的所有不同元素。
所以,如果输入像
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]
为了解决这个问题,我们将遵循以下步骤-
定义一个功能
sortRows()
。这将采用矩阵n:=行数
对于0到n范围内的i,执行
排序列表矩阵[i]
在主要方法中,请执行以下操作-
n:=行数
sortRows(矩阵)
current_idx:=大小为n的列表,以0填充
对于0到n范围内的i,执行
current_idx [i]:= 0
f:= 0
当current_idx [0] <n时,执行
从循环中出来
显示值
而(current_idx [i] <n和matrix [i] [current_idx [i]] <=值,
如果matrix [i,current_idx [i]-1]与值不同,则
如果current_idx [i]与n相同,则
current_idx [i]:= current_idx [i] + 1
存在:=错误
f:= 1
从循环中出来
值:=矩阵[0,current_idx [0]]
目前:=正确
对于1到n范围内的i,执行
如果存在非零,则
如果f与1相同,则
current_idx [0]:= current_idx [0] + 1
示例
让我们看下面的实现以更好地理解-
MAX = 100def 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,
以上是 在Python中查找矩阵所有行共有的不同元素 的全部内容, 来源链接: utcz.com/z/322276.html