找出最长的1序列的开始位置 [英] find the start position of the longest sequence of 1's

查看:87
本文介绍了找出最长的1序列的开始位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到数组中最长1序列的开始位置:

I want to find the start position of the longest sequence of 1's in my array:

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

我正在按照答案来找到最长序列的长度.但是,我无法确定位置.

I am following this answer to find the length of the longest sequence. However, I was not able to determine the position.

推荐答案

this solution 的启发,这是一个矢量化的解决问题的方法-

Inspired by this solution, here's a vectorized approach to solve it -

# 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

这篇关于找出最长的1序列的开始位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆