numpy二维数组在其中查找精确的二维数组



在这种情况下,我有一个3x5的2-D numpy数组,我想在这个3x5中找到唯一的2-D数组,例如:

[[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 1.]
[0. 0. 1. 1. 1.]]

我想在这个二维数组中找到一个1的2x2,它应该返回true,所以它可能看起来像这个

A = [[0. 0. 1. 0. 0.],
[0. 0. 0. 1. 1.],
[0. 0. 1. 1. 1.]]
B = [[1. 1.],
[1. 1.]]
somfunction(A,B)
=> True

以下是一个暴力解决方案:

import numpy as np
A = np.array([[0, 0, 1, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 1, 1, 1]])
B = np.array([[1, 1],
[1, 1]])

def isequal(A, B):
if np.sum(A-B) == 0:
return True
return False
def isBinA(A, B):
if B.shape[0] > A.shape[0] or B.shape[1] > A.shape[1]:
return False
else:
for i in range(A.shape[0]-B.shape[0]+1):
for j in range(A.shape[1]-B.shape[1]+1):
if isequal(A[i:i+B.shape[0], j:j+B.shape[1]], B):
# edit to change A's value
A[i:i+B.shape[0], j:j+B.shape[1]] = 2 * B # or any value you want.
return True
return False
print(isBinA(A, B))

递归解决方案:

def isBinA_rec(A, B, i, j):
AA = A[i:i+B.shape[0],j:j+B.shape[1]]
if AA.shape[0] == B.shape[0] and AA.shape[1] == B.shape[1] and np.sum(AA-B) == 0:
return True
if i >= A.shape[0] - B.shape[0] or j >= A.shape[1] - B.shape[1]:
return False
return isBinA_rec(A, B, i+1, j) or isBinA_rec(A, B, i, j+1) or isBinA_rec(A, B, i+1, j+1)

我们可以称之为

print(isBinA_rec(A, B, 0, 0))

最新更新