Python实现自定义排除规则的孤立索引识别
问题描述
现有基于Python编写的孤立索引识别代码,基础判定规则为:索引需至少拥有2个相邻邻居才不属于孤立索引,坐标(i,j)的合法邻居仅包含正交相邻的四个坐标:(i+1,j),(i-1,j),(i,j+1),(i,j-1)。现需在现有逻辑基础上新增两项排除规则:
- 始终排除索引
(0,0),不将其判定为孤立索引 - 若某索引是最后一行的唯一索引,则不对其做孤立判定
预期测试结果
- 输入
indices = [(0, 0),(0,1),(1,0),(2,0)]时,预期返回的孤立索引仅为(0,1) - 输入
indices = [(0, 0),(1,0),(2,0)]时,预期无孤立索引返回
修正方案
原有代码的邻居计数逻辑本身符合正交相邻判定规则,仅需要在孤立判定环节前新增两个排除规则的判断分支即可,修正后完整代码如下:
import numpy as np def get_isolated_indices(indices): indices = np.array(indices) indices = indices[np.argsort(indices[:, 0])] # 约定坐标对第一个值为行号,第二个值为列号 max_vals = np.max(indices, axis=0) max_row = max_vals[0] rows = indices[:, 0] cols = indices[:, 1] # 提前统计最后一行的索引总数,用于第二条排除规则判定 last_row_count = np.sum(rows == max_row) isolated = [] for i in range(len(indices)): this_row = indices[i, 0] this_col = indices[i, 1] # 排除规则1:直接跳过(0,0)的孤立判定 if (this_row, this_col) == (0, 0): continue # 排除规则2:直接跳过最后一行唯一索引的孤立判定 if this_row == max_row and last_row_count == 1: continue # 计算合法相邻坐标范围 nearby_row_vals = list(range(max(0, this_row - 1), min(this_row + 1, max_vals[0]) + 1)) nearby_col_vals = list(range(max(0, this_col - 1), min(this_col + 1, max_vals[1]) + 1)) same_row_mask = rows == this_row same_col_mask = cols == this_col diff_rows_mask = (rows >= np.min(nearby_row_vals)) & (rows <= np.max(nearby_row_vals)) & (rows != this_row) diff_cols_mask = (cols >= np.min(nearby_col_vals)) & (cols <= np.max(nearby_col_vals)) & (cols != this_col) intersection1 = np.logical_and(same_row_mask, same_col_mask) intersection2 = np.logical_and(same_row_mask, diff_cols_mask) intersection3 = np.logical_and(diff_rows_mask, same_col_mask) final_intersection = np.logical_or(np.logical_or(intersection1, intersection2), intersection3) # 减去自身重复计数,得到真实正交邻居数量 num_neighbors = np.sum(final_intersection) - 1 if num_neighbors <= 1: isolated.append((this_row, this_col)) return isolated # 测试用例验证 if __name__ == "__main__": indices1 = [(0, 0),(0,1),(1,0),(2,0)] print("测试用例1结果:", get_isolated_indices(indices1)) # 输出 [(0, 1)] indices2 = [(0, 0),(1,0),(2,0)] print("测试用例2结果:", get_isolated_indices(indices2)) # 输出 []
验证说明
运行上述代码后两个测试用例输出完全符合预期:
- 测试用例1中
(0,0)被规则排除,(2,0)作为最后一行唯一索引被规则排除,(1,0)拥有(0,0)、(2,0)两个邻居不满足孤立条件,仅(0,1)只有1个邻居被判定为孤立 - 测试用例2中
(0,0)被规则排除,(2,0)作为最后一行唯一索引被规则排除,(1,0)拥有(0,0)、(2,0)两个邻居不满足孤立条件,最终无孤立索引返回
内容的提问来源于stack exchange,提问作者Wiz123
相关产品推荐
相关产品推荐

