如何获得矩阵中三角形的总和

时间:2018-03-25 14:15:40

标签: python-3.x numpy

我对numpy的经验有限。 如何在0/1方阵中找到triange的总和?

0 1 0
1 1 1 

三角形的大小是2;

0 0 1 0 0
0 1 1 1 0
1 1 1 1 1 

triange的大小是3;

矩阵:

1 1 1 1 1

0 1 1 1 1

1 1 1 1 1

1 1 1 1 1

结果:[(2,8),(3,2)],我正在插入并写了一个剧本,我认为这不好,所以有人给出更好的答案吗?

# -*- coding: utf-8 -*-

import numpy as np
import math

a=np.random.randint(0,2,size=[20,20])
print(a)
x_a, y_a = a.shape

def oneTriangle(list):
    tri=np.ones(list,dtype=int)
    tri_upper_no_diag=np.triu(tri,k=1)[::-1]
    tri_lower_no_diag=np.tril(tri,k=0)

    a=np.concatenate((tri_upper_no_diag,tri_lower_no_diag),axis=1)

    b=np.delete(a,0,axis=1)

    return b

def subsearch(a, b):
    number = 0
    x_b, y_b = b.shape

    for i in range(0,a.shape[0]):
        for j in range(0,a.shape[1]):
            #print(i,j)
            c = a[i:(i+x_b), j:(j+y_b)]
            if((c.shape == b.shape) and ((c == b).all())):
                #print(c,'\n', b)
                number = number + 1
    return (number, x_b)

min_value = min(x_a, y_a)
for i in range(2, min_value):
    b = oneTriangle([i, i])
    #print(b)
    number = subsearch(a, b)
    print(number)

0 个答案:

没有答案