这是我的矩阵:
1 1 2 5 6 1
5 6 8 5 6 7
10 12 10 12 11 11
8 10 5 6 8 9
6 5 10 12 15 19
我希望找到saddle points。
鞍点的COORDINATES 应为:
2 0
2 2
0 4
所以我的问题是。有人可以告诉我,如何在Python中制作它? :)
答案 0 :(得分:2)
这是一种Python方法,它汇集了所有行/列分钟和最大值的索引列表,然后使用set操作来查找它们的交集:
def allSaddles(matrix):
rowmins = []
rowmaxs = []
colmins = []
colmaxs = []
for i,row in enumerate(matrix):
m = min(row)
M = max(row)
for j,x in enumerate(row):
if x == m: rowmins.append((i,j))
if x == M: rowmaxs.append((i,j))
t = [list(column) for column in zip(*matrix)] #transpose of matrix
for j,col in enumerate(t):
m = min(col)
M = max(col)
for i,x in enumerate(col):
if x == m: colmins.append((i,j))
if x == M: colmaxs.append((i,j))
return (set(rowmins) & set(colmaxs)) | (set(rowmaxs) & set(colmins))
M = [[1,1,2,5,6,1],
[5,6,8,5,6,7],
[10,12,10,12,11,11],
[8,10,5,6,8,9],
[6,5,10,12,15,19]]
print(allSaddles(M))
输出:{(0, 4), (2, 0), (2, 2)}
答案 1 :(得分:1)
这是我在python中的鞍点查找器
import numpy as np
def is_saddle(row, column, *args):
index = 0
size = row * column
matrix = np.arange(size).reshape(row, column)
for i in range(row):
for j in range(column):
matrix[i][j] = args[0][index]
index = index + 1
print(matrix)
for item_row in matrix:
column_number = 0
min_item = np.amin(item_row)
for i in range(len(item_row)):
if min_item == item_row[i]:
row_number = i
reversed_matrix = matrix.transpose()
max_item = np.amax(reversed_matrix[row_number])
if max_item == min_item:
print("saddle point found : {}".format(min_item))
return matrix
row = input("enter row")
column = input("enter column")
matrix = input("enter the matrix items")
is_saddle(row, column, matrix)
输入样本:行= 2,列= 3,矩阵=(1,2,3,4,5,6)
答案 2 :(得分:0)
这是一种不同的制作方法。请注意,输入矩阵是np.ndarray
:
def saddles(mat : np.ndarray) -> list:
"""
returns the list of all saddle points of the input matrix
"""
(N, M) = mat.shape
jMax = np.argmax(mat, axis = 1) # index of col for max in each row
iMin = np.argmin(mat, axis = 0) # index of row for min in each col
IJMax = [(i,jMax[i]) for i in range(N)] # list of indexes of max of each row
IJMin = [(iMin[j],j) for j in range(M)] # list of indexes of min of each col
maxRowMinCol = list(set(IJMax) & set(IJMin)) # max of row, min of col
iMax = np.argmax(mat, axis = 0) # index of row for max in each col
jMin = np.argmin(mat, axis = 1) # index of col for min in each row
IJMax = [(iMax[j],j) for j in range(M)] # list of indexes of max of each col
IJMin = [(i,jMin[i]) for i in range(N)] # list of indexes of min of each row
minRowMaxCol = list(set(IJMax) & set(IJMin)) # min of row, max of col
return maxRowMinCol + minRowMaxCol