简体   繁体   English

如何使用python查找矩阵中平方的最大和

[英]How to find the biggest sum of a square in a matrix using python

I am trying to write a code that will give me the biggest sum of a square in a matrix. 我正在尝试编写代码,以使我得到矩阵中一个正方形的最大和。

note: the values have to be next to each other while forming the shape of a square. 注意:在形成正方形形状时,这些值必须彼此相邻。

note 2: I am only allowed to use functions, importing anything isn't allowed currently in the class I am taking. 注意2:我只允许使用函数,而我正在上的课目前不允许导入任何内容。

For example: 例如:

 max_mat_square([[1,2.5,3],
                 [4,-4,6],
                 [0.5,-1,5]])

[7.5]

Now this is the code I have: 现在这是我的代码:

def max_mat_square(mat):
    sum1 = []
    for i in range(len(mat[:-1])):
        print i
        for j in range(len(mat[1:])):
                print 'index' , j
                sum1.append([float(mat[i][j]) + float(mat[i+1][j])+float(mat[i][j+1])+float(mat[i+1][j+1])])
    return max(sum1)

Now the code works fine with the first example, However whenever I run this matrix throw it: 现在,代码在第一个示例中运行良好,但是,每当我运行此矩阵时,都将其抛出:

max_mat_square([[1,2], [3,4], [5,6]])

I get 'list index out of range' error, The result I want for this matrix is 18. 我收到“列表索引超出范围”错误,此矩阵的结果是18。

I tried a lot of methods to fix the error, but none of them worked. 我尝试了很多方法来纠正错误,但是没有一个起作用。

The problem is your inner for loop. 问题是您的内部for循环。 You should have j starting from 0 up to the row's second last index: 您应该让j从0开始到该行的倒数第二个索引:

for j in range(len(mat[i][:-1])):
    ...

So your final function becomes: 因此,您的最终功能变为:

def max_mat_square(mat):
    sum1 = []
    for i in range(len(mat[:-1])):
        print(i)
        for j in range(len(mat[i][:-1])):
                print('index' , j)
                sum1.append([float(mat[i][j]) + float(mat[i+1][j])+float(mat[i][j+1])+float(mat[i+1][j+1])])
    return max(sum1)

I think your first example works only co-incidentally because of the shape of your matrix. 由于矩阵的形状,我认为您的第一个示例只能同时出现。 Currently the slicing used in that loop means you are selecting from the second sub-list to the end: 当前,该循环中使用的切片意味着您正在从第二个子列表中选择结尾:

mat[1:]
>> [[3,4], [5,6]]

Which implies you'll try to loop through each element with range(2) which will go out of range. 这意味着您将尝试遍历range(2)每个元素。

Change the second for statement as follows: 更改第二个for语句,如下所示:

def max_mat_square(mat):
    sum1 = []
    for i in range(len(mat[:-1])):
        for j in range(len(mat[i])-1):
            print (i , j)
            sum1.append([float(mat[i][j]) + float(mat[i+1][j])+float(mat[i][j+1])+float(mat[i+1][j+1])])
    return max(sum1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM