码迷,mamicode.com
首页 > 其他好文 > 详细

20190110-用笨办法找到二维矩阵的鞍点

时间:2019-01-10 21:44:09      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:嵌套   矩阵   oca   als   max   list   font   pen   数组   

1:找出一个多维数组的鞍点,即该元素在该行上最大,在该列上最小,也可能没有鞍点

a = [
    [1,2,3,4],
    [4,5,6,2],
    [7,0,5,2],
    [11,10,7,9]]

解题思路如下:

step1:先找出每行的最大值,及其index,输出最大值,即所在行和列作为要给list存如result列表中,函数写法如下:

def find_saddle_max_point(s):
    result =[]
    #用result存储每行最大值以及其index
    for i in range(len(s)):
        #遍历次数,即一共有多少个行,如例子中一共有4行,该值等于a的元素个数
        max =s[i][0]
#设定每行的最大值为第一个
        location =[]
#新建一个location列表来存储该值在外层的index和内层的index
        index=0
#设定最大值所在的列的index值为0
        for j in range(len(s[i])):           
            #遍历每行的每个值
            if s[i][j]>max:
                max = s[i][j]
                index =j
#找出最大值以及最大值所在列,即j的值
        location.append(i)
        location.append(index)
#存入横向列表坐标和纵向坐标值
        result.append((max,location))
#将最大值及所在的location(包括横向坐标和纵向坐标)存如result中
    return result
print(find_saddle_max_point(a))

step2:找出二维矩阵每列最小值,函数写法同step1

def find_saddle_min_point(s):
    result =[]
    for i in range(len(s[0])):
        #遍历列的次数,如a有4列,列的遍历次数等于a的嵌套列表的长度
        min = s[0][i]
#设定最小值为每列第一个
        location=[]
        index=0
        for j in range(len(s)):
            #遍历每列的值
            if s[j][i]<min:
                min =s[j][i]
                index = j
        location.append(index)
        location.append(i)
#将每列的最小值所在的index存如location列表中
        result.append((min,location))
#将每列的最小值以及所在的location存如result中
    return result
print(find_saddle_min_point(a))

step3:遍历step1和step2生成的列表,如果有最大值和最小值重复,并且index一样,即2个列表中有重复元素则为二维数组的鞍点

#step3:如果最小值与最大值重复,并且其index一样,则为鞍点
def find_saddle(a):
    list1 = find_saddle_max_point(a)
    list2 = find_saddle_min_point(a)
    for i in list1:
        if i in list2:
            return i
    else:
        return False
print(find_saddle(a))

 

 

20190110-用笨办法找到二维矩阵的鞍点

标签:嵌套   矩阵   oca   als   max   list   font   pen   数组   

原文地址:https://www.cnblogs.com/hyj691001/p/10252327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!