使用scipy;具体来说,使用scipy.ndimage.label 函数,它将连接的序列标记在一起。
import scipy, scipy.ndimage
# N and grid dictionary are already known
G = scipy.zeros([N,N])
for k, v in grid.iteritems():
if v.lower() == 'yes':
G[tuple(k)] = 1
elif v.lower() == 'no':
G[tuple(k)] = -1
def get_consecutive_spaces(G, chain=5):
sequences = []
# Generate a pattern for each directional sequence. (1) Horizontal,
# (2) vertical, (3) top-left to bottom-right diagonal, (4) bottom-left
# to top-right diagonal
patterns = [scipy.ndimage.label(G == 0, structure = scipy.array([[0,0,0],
[1,1,1],
[0,0,0]])),
scipy.ndimage.label(G == 0, structure = scipy.array([[0,1,0],
[0,1,0],
[0,1,0]])),
scipy.ndimage.label(G == 0, structure = scipy.array([[1,0,0],
[0,1,0],
[0,0,1]])),
scipy.ndimage.label(G == 0, structure = scipy.array([[0,0,1],
[0,1,0],
[1,0,0]]))]
# Loop over patterns, then find any labelled sequence >= a size of chain=5
for lab_arr, n in patterns:
for i in range(1, n+1):
b = lab_arr == i
b_inds = scipy.where(b)
if len(b_inds[0]) < chain:
continue
sequences.append((tuple(b_inds[0]), tuple(b_inds[1])))
return sequences
例如
>>> G = scipy.sign(scipy.random.random([12,12]) - 0.5)*(scipy.random.random([12,12]) < 0.5)
>>> print G
[[-0. 1. -1. 1. 1. -1. 1. 0. -0. 1. 0. -0.]
[ 1. 1. -0. -0. -1. 1. 1. -1. -1. 1. -0. -1.]
[ 0. 1. 1. 1. 0. 1. -0. 0. 0. 0. -0. 0.]
[ 1. -0. -1. 0. -1. -0. 1. 0. -0. -0. -0. 1.]
[-0. 1. -1. 1. -0. -0. -1. -0. 1. 1. -0. 0.]
[ 0. -1. 1. -0. 1. 0. -0. -1. -1. -0. 0. -1.]
[-1. -0. 0. -1. -1. -0. -1. 0. 0. 0. -1. 0.]
[-0. 1. 0. 0. 0. 1. 1. -1. 0. -0. -1. 0.]
[ 1. 1. 0. 1. -1. -1. 0. 0. -1. 1. 0. 0.]
[-0. 0. 0. -1. -0. -1. 1. -0. 0. 1. 1. 0.]
[-1. 1. -1. 1. 0. 1. 0. 1. 1. 1. 1. 0.]
[-1. 1. -0. 0. -1. 0. -0. -1. 1. -1. -0. 0.]]
>>> sequences = get_consecutive_spaces(G)
>>> for s in sequences: print s
((2, 2, 2, 2, 2, 2), (6, 7, 8, 9, 10, 11))
((0, 1, 2, 3, 4, 5), (10, 10, 10, 10, 10, 10))
((6, 7, 8, 9, 10, 11), (11, 11, 11, 11, 11, 11))
((0, 1, 2, 3, 4, 5, 6, 7), (11, 10, 9, 8, 7, 6, 5, 4))
((2, 3, 4, 5, 6), (6, 5, 4, 3, 2))
((4, 5, 6, 7, 8), (11, 10, 9, 8, 7))
注意,返回大于或等于链的序列;不将自身限制为长度仅为 5 的序列。将其更改为仅 5 的长度是一个简单的修复。