You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求可判定并统计目标二进制序列的函数或工具包

Solution for Extracting Subsequence Lengths from Binary Vector

Got it, let's break down how to solve this problem efficiently. The goal is to take a binary vector (composed of 1s and 0s) where each valid subsequence starts with a 1 and ends right before the next 1 (or the end of the vector if there's no subsequent 1), then output a vector of each subsequence's length.

Core Logic

  • First, identify all the positions (indices) where the value is 1 in your input vector.
  • Calculate the distance between consecutive 1s—this gives the length of the subsequence starting at the first 1 and ending just before the next one.
  • For the final subsequence (starting at the last 1), calculate its length as the distance from the last 1's index to the end of the vector.

Python Implementation

Using NumPy (Best for Large Vectors)

NumPy makes this super concise and efficient, especially with large datasets:

import numpy as np

# Example input binary vector
binary_vec = np.array([1, 0, 1, 0, 0, 0, 1, 0, 0])

# Get indices of all 1s
ones_indices = np.where(binary_vec == 1)[0]

# Calculate lengths by diffing indices (append vector length to cover the final subsequence)
subseq_lengths = np.diff(np.append(ones_indices, len(binary_vec)))

print(subseq_lengths)  # Output: [2 4 3]

Pure Python (No External Libraries)

If you prefer not to use NumPy, here's a straightforward pure Python approach:

# Example input binary vector
binary_vec = [1, 0, 1, 0, 0, 0, 1, 0, 0]

# Collect indices of all 1s
ones_indices = [idx for idx, val in enumerate(binary_vec) if val == 1]

# Calculate each subsequence's length
subseq_lengths = []
for i in range(len(ones_indices)):
    if i < len(ones_indices) - 1:
        # Distance between current 1 and next 1
        subseq_lengths.append(ones_indices[i+1] - ones_indices[i])
    else:
        # Distance from last 1 to end of vector
        subseq_lengths.append(len(binary_vec) - ones_indices[i])

print(subseq_lengths)  # Output: [2, 4, 3]

R Implementation

For R users, here's a clean solution using base R functions:

# Example input binary vector
binary_vec <- c(1, 0, 1, 0, 0, 0, 1, 0, 0)

# Get positions of all 1s
ones_indices <- which(binary_vec == 1)

# Calculate lengths (append vector length to handle final subsequence)
subseq_lengths <- diff(c(ones_indices, length(binary_vec)))

print(subseq_lengths)  # Output: 2 4 3

Edge Cases Handled

  • Single 1 followed by 0s: e.g., [1,0,0] → outputs [3]
  • Vector ends with a 1: e.g., [1,0,1] → outputs [2, 1]
  • Only one element (1): e.g., [1] → outputs [1]

内容的提问来源于stack exchange,提问作者Aggle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:15:17