generate functionTue, 28 Feb 2023

Write a function that finds the sum of even elements on the main diagonal of a square matrix (namely, even elements, not elements in even positions!). If there are no even elements, then output 0. Use the numpy library.

import numpy as np def diagonal_sum(matrix): diagonal = np.diagonal(matrix) return sum([x for x in diagonal if x%2==0]) matrix = np.array([[1,2,3], [4,5,6], [7,8,9]]) print(diagonal_sum(matrix))

Questions about programming?Chat with your personal AI assistant