找出最长的连续1序列的起始位置。

15

我想要找到数组中最长的连续1序列的起始位置:

a1=[0,0,1,1,1,1,0,0,1,1]
#2

我正在遵循这个答案来找到最长序列的长度。然而,我无法确定位置。

8个回答

16

this solution启发,这里提供了一种向量化的方法来解决它 -

# Get start, stop index pairs for islands/seq. of 1s
idx_pairs = np.where(np.diff(np.hstack(([False],a1==1,[False]))))[0].reshape(-1,2)

# Get the island lengths, whose argmax would give us the ID of longest island.
# Start index of that island would be the desired output
start_longest_seq = idx_pairs[np.diff(idx_pairs,axis=1).argmax(),0]

样例运行 -

In [89]: a1 # Input array
Out[89]: array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1])

In [90]: idx_pairs # Start, stop+1 index pairs
Out[90]: 
array([[ 2,  6],
       [ 8, 10]])

In [91]: np.diff(idx_pairs,axis=1) # Island lengths
Out[91]: 
array([[4],
       [2]])

In [92]: np.diff(idx_pairs,axis=1).argmax() # Longest island ID
Out[92]: 0

In [93]: idx_pairs[np.diff(idx_pairs,axis=1).argmax(),0] # Longest island start
Out[93]: 2

漂亮的解决方案! - Kai Wang

3

使用groupby()更紧凑的单行代码。在原始数据上使用enumerate()来保留开始位置,直到分析管道结束,最终得到包含非零运行的起始位置和长度的元组列表[(2, 4), (8, 2)]:

from itertools import groupby

L = [0,0,1,1,1,1,0,0,1,1]

print max(((lambda y: (y[0][0], len(y)))(list(g)) for k, g in groupby(enumerate(L), lambda x: x[1]) if k), key=lambda z: z[1])[0]

lambda: xgroupby()的关键函数,因为我们枚举了L。

lambda: y打包我们需要的结果,因为我们只能评估g一次,而不保存。

lambda: z是用于max()提取长度的关键函数。

按预期输出“2”。


2

这个方法似乎可行,使用了itertools中的groupby函数,而且只需要遍历一次列表:

from itertools import groupby

pos, max_len, cum_pos = 0, 0, 0

for k, g in groupby(a1):
    if k == 1:
        pat_size = len(list(g))
        pos, max_len = (pos, max_len) if pat_size < max_len else (cum_pos, pat_size)
        cum_pos += pat_size
    else:
        cum_pos += len(list(g))

pos
# 2
max_len
# 4

1
你可以使用for循环,并检查下几个项(长度为m,其中m是最大长度),是否与最大长度相同:
# Using your list and the answer from the post you referred
from itertools import groupby
L = [0,0,1,1,1,1,0,0,1,1]
m = max(sum(1 for i in g) for k, g in groupby(L))
# Here is the for loop
for i, s in enumerate(L):
    if len(L) - i + 2 < len(L) - m:
        break
    if s == 1 and 0 not in L[i:i+m]:
        print i
        break

这将给出:
2

1

另一种在单个循环中完成的方法,但不使用 itertoolsgroupby

max_start = 0
max_reps = 0
start = 0
reps = 0
for (pos, val) in enumerate(a1):
    start = pos if reps == 0 else start
    reps = reps + 1 if val == 1 else 0
    max_reps = max(reps, max_reps)
    max_start = start if reps == max_reps else max_start

这也可以使用reduce以一行代码的方式完成:

max_start = reduce(lambda (max_start, max_reps, start, reps), (pos, val): (start if reps == max(reps, max_reps) else max_start, max(reps, max_reps), pos if reps == 0 else start, reps + 1 if val == 1 else 0), enumerate(a1), (0, 0, 0, 0))[0]

在Python 3中,你无法在lambda参数定义中解包元组,因此最好先使用def定义函数:
def func(acc, x):
    max_start, max_reps, start, reps = acc
    pos, val = x
    return (start if reps == max(reps, max_reps) else max_start,
            max(reps, max_reps),
            pos if reps == 0 else start,
            reps + 1 if val == 1 else 0)

max_start = reduce(func, enumerate(a1), (0, 0, 0, 0))[0]

在这三种情况中,max_start 给出了您的答案(即 2)。

0
使用第三方库{{link1:more_itertools}}: 给定
import itertools as it

import more_itertools as mit


lst = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1]

代码

longest_contiguous = max([tuple(g) for _, g in it.groupby(lst)], key=len)
longest_contiguous    
# (1, 1, 1, 1)

pred = lambda w: w == longest_contiguous
next(mit.locate(mit.windowed(lst, len(longest_contiguous)), pred=pred))
# 2

详情请参阅 more_itertools.locate 的文档字符串,了解这些工具的工作原理。


0

针对仅使用Numpy的另一种解决方案,我认为这应该适用于所有情况。但最得票的解决方案可能更快。

tmp = np.cumsum(np.insert(np.array(a1) != 1, 0, False))  # value of tmp[i+1] was not incremented when a1[i] is 1
# [0, 1, 2, 2, 2, 2, 2, 3, 4, 4, 4]

values, counts = np.unique(tmp, return_counts=True)
# [0, 1, 2, 3, 4], [1, 1, 5, 1, 3]

counts_idx = np.argmax(counts)
longest_sequence_length = counts[counts_idx] - 1
# 4

longest_sequence_idx = np.argmax(tmp == values[counts_idx])
# 2

0
我已经在haggis.npy_util.mask2runs中实现了一个用于numpy数组的运行搜索函数。您可以像这样使用它:
runs, lengths = mask2runs(a1, return_lengths=True)
result = runs[lengths.argmax(), 0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接