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

numpy整数行正数值岛处理:判断最接近行索引元素是否在首尾

Numpy正数值岛任务实现方案

任务说明

需要对numpy整数数组的指定行完成三项处理:

  • 识别该行内所有正数值岛(连续正数值组成的序列)的位置
  • 统计每个正数值岛的长度
  • 对每个正数值岛,判断岛内取值最接近行索引的元素是否位于该岛的第一个或最后一个位置,返回对应的布尔值列表

已有实现(前两项任务)

现有已经完成前两项功能的代码如下:

import numpy as np

arr = np.array([[-1, -4, -2, -8,  8, -3, -5, -6,  7],
                [-4, -9, -1,  3,  8, -7, -6,  2, -5],
                [ 4,  6,  9,  3, -1, -2,  5,  4,  8],
                [ 5, -1,  2,  5,  6,  7, -3, -4,  1]])

row_idx = 2
arr_row = arr[row_idx]

mask = arr_row > 0                    
changes = np.concatenate(([mask[0]], mask[:-1] != mask[1:], [mask[-1]]))

isl_idx = np.where(changes)[0]      # 岛屿的起始索引
pos_idx = isl_idx[::2]              # 正数值岛的起始索引
print('pos_idx = ', pos_idx)

pos_len = np.diff(isl_idx)[::2]     # 正数值岛的长度
print('pos_len = ', pos_len)

当row_idx = 2时,上述代码输出为:

pos_idx = [0, 6]
pos_len = [4, 3]

第三项任务实现代码

在已有代码后追加以下内容即可完成第三项功能:

firstLast = []
for start, length in zip(pos_idx, pos_len):
    # 提取当前正数值岛的元素
    curr_island = arr_row[start: start + length]
    # 计算所有元素与行索引的绝对差值
    abs_diff = np.abs(curr_island - row_idx)
    # 找到差值最小的元素的所有位置
    min_diff_pos = np.nonzero(abs_diff == abs_diff.min())[0]
    # 判断是否有最小差值元素位于岛的首尾
    firstLast.append(any(pos in (0, length - 1) for pos in min_diff_pos))

print('firstLast = ', firstLast)

运行效果

当row_idx = 2时,输出结果为firstLast = [True, False],和预期一致:

  • 第一个正数值岛范围是索引0到3,元素为[4,6,9,3],和行索引2差值最小的是3,位于岛的最后一个位置,返回True
  • 第二个正数值岛范围是索引6到8,元素为[5,4,8],和行索引2差值最小的是4,位于岛的中间位置,返回False

边界兼容说明

如果某个岛内存在多个和行索引差值相同的最小元素,只要其中任意一个位于首尾位置,就会返回True,符合常规业务逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:45:03