gpt4 book ai didi

python - 找到最长的 1 序列的起始位置

转载 作者:太空狗 更新时间:2023-10-29 22:18:20 25 4
gpt4 key购买 nike

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

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

我正在关注这个 answer找到最长序列的长度。但是,我无法确定位置。

最佳答案

灵感来自 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]

sample 运行-

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

关于python - 找到最长的 1 序列的起始位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com