Python矩阵处理:定位元素1并统计其对角线上其他1的数量(修复代码)
问题修正:统计矩阵对角线中其他1的数量
原始矩阵
matrix = [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0] ]
需求说明
定位矩阵中每个值为1的元素,检查该元素的所有对角线并统计对角线上其他1的数量,将结果存储到变量中。
原代码问题
原代码运行异常:当矩阵中所有1的对角线无重叠时,代码输出结果为4,而正确结果应为0(即没有1的对角线上存在其他1)。
原代码:
def check_diagonals(matrix, row, col): # Define the directions for diagonals: up-left, up-right, down-left, down-right directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)] # List to store the values found in diagonals diagonal_count=0 for dr, dc in directions: r, c = row, col while 0 <= r < len(matrix) and 0 <= c < len(matrix[0]): if(matrix[r][c]==1): diagonal_count+=1 r += dr c += dc return diagonal_count def search_and_check(matrix): for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 1: diagonals = check_diagonals(matrix, i, j) print("Diagonal count:", diagonals) # Example usage: matrix =[[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0]] search_and_check(matrix)
问题原因
- 遍历对角线时,从当前元素自身开始计数,每个方向的循环都统计了当前元素,导致每个1被重复统计4次(四个方向各一次),最终得到错误的结果4。
- 没有排除当前元素,错误地将自身计入了"其他1"的统计范围。
修正后的代码
def check_diagonals(matrix, row, col): # 定义四个对角线方向:左上、右上、左下、右下 directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)] diagonal_count = 0 for dr, dc in directions: # 跳过当前元素,直接从相邻的对角线位置开始遍历 r, c = row + dr, col + dc while 0 <= r < len(matrix) and 0 <= c < len(matrix[0]): if matrix[r][c] == 1: diagonal_count += 1 r += dr c += dc return diagonal_count def search_and_check(matrix): # 用字典存储每个1的位置对应的统计结果 result = {} for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 1: count = check_diagonals(matrix, i, j) result[(i, j)] = count print(f"位置({i}, {j})的对角线上其他1的数量: {count}") return result # 示例使用 matrix = [ [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0] ] search_and_check(matrix)
修正说明
- 调整对角线遍历的起始位置:直接从当前元素的相邻对角线位置开始,彻底排除了对自身的统计。
- 添加结果存储字典,方便后续调用统计数据。
- 优化输出信息,明确展示每个1的位置对应的统计结果。
内容的提问来源于stack exchange,提问作者Marcelo Pavani
相关产品推荐
相关产品推荐

