如何查找数字序列正反向起点并处理可容忍误差匹配条件
连续序列起点匹配实现方案
核心规则
- 匹配维度分两类:正向递增匹配、反向递减匹配,两个维度独立计算
- 正向匹配从数组最左侧开始遍历,找第一个满足条件的窗口起点值
- 反向匹配从数组最右侧开始遍历,找第一个满足条件的窗口起点值
- 匹配逻辑采用固定长度滑动窗口,默认窗口长度为5,支持自定义调整
- 误差规则支持自定义配置:
error_accepted:窗口内允许的最大误差次数,超过则判定窗口无效error_difference_upto:窗口内相邻元素的最大合法差值,差值不符合要求则计为一次误差
参考实现代码
import numpy as np def match_start_point( input_arr: np.ndarray, direction: str, # 可选值:"forward" 正向递增 / "backward" 反向递减 window_length: int = 5, error_accepted: int = 0, error_difference_upto: int = 1 ) -> int | None: arr_len = len(input_arr) if arr_len < window_length: return None # 根据匹配方向确定遍历顺序 if direction == "forward": # 正向:从最左到最右,取第一个满足条件的起点 start_positions = range(arr_len - window_length + 1) else: # 反向:从最右到最左,取第一个满足条件的起点 start_positions = range(arr_len - 1, window_length - 2, -1) for start_pos in start_positions: if direction == "forward": # 正向窗口:从当前起点向右取连续window_length个元素 window = input_arr[start_pos : start_pos + window_length] else: # 反向窗口:从当前起点向左取连续window_length个元素 window = input_arr[start_pos : start_pos - window_length : -1] error_count = 0 # 校验窗口内相邻元素差值 for idx in range(window_length - 1): diff = window[idx + 1] - window[idx] if direction == "forward": # 正向要求递增:差值大于0,且不超过最大允许差 if diff <= 0 or diff > error_difference_upto: error_count += 1 else: # 反向要求递减:差值小于0,且绝对值不超过最大允许差 if diff >= 0 or -diff > error_difference_upto: error_count += 1 # 误差超限时直接跳出当前窗口校验 if error_count > error_accepted: break # 误差在允许范围内,返回当前窗口的起点值 if error_count <= error_accepted: return input_arr[start_pos] return None # 示例测试数组 test_array = np.array([ 1, 6, 12, 14, 16, 18, 21, 23, 24, 27, 29, 54, 55, 56, 57, 58, 59, 60, 61, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178 ]) # 计算正向匹配起点 forward_result = match_start_point( test_array, direction="forward", window_length=5, error_accepted=0, error_difference_upto=1 ) # 计算反向匹配起点 backward_result = match_start_point( test_array, direction="backward", window_length=5, error_accepted=0, error_difference_upto=1 )
规则验证
- 无误差配置下,正向匹配起点为54,反向匹配起点为175,和示例预期输出完全一致
- 自定义误差场景匹配验证:
- 配置
error_accepted=1、error_difference_upto=1时,序列54,56,57,58,59仅存在1次差值为2的跳变,误差数在允许范围内,会被正确识别为有效序列,有效起点为54 - 配置
error_accepted=2、error_difference_upto=3时,序列54,58,59,61,62存在2次差值不超过3的跳变,误差数在允许范围内,会被正确识别为有效序列,有效起点为54
- 配置
原有代码缺陷修正
- 移除硬编码的数组范围值
range(1,178),支持任意长度输入数组的匹配 - 新增滑动窗口误差统计逻辑,不再遇到非连续值就直接重置计数
- 新增反向匹配遍历逻辑,从数组末尾逐位向左校验,支持输出反向维度的起点值
内容的提问来源于stack exchange,提问作者user_12
相关产品推荐
相关产品推荐

