gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Create a Python function that takes a square matrix (2D list) as input and checks if all…
- User
Create a Python function that takes a square matrix (2D list) as input and checks if all the elements in the diagonals are the same. If they are, the function should return True; otherwise, it should return False. For example, given the matrix [[1, 2, 3], [4, 1, 2], [3, 4, 1]], the function should return True
- Assistant
Sure! Below is the Python function that checks if all the elements in the diagonals of a given square matrix are the same:
def check_diagonals(matrix): if not matrix or not all(len(row) == len(matrix) for row in matrix): raise ValueError("Input must be a square matrix") n = len(matrix) # Get the value of the main diagonal and the anti-diagonal main_diagonal_value = matrix[0][0] anti_diagonal_value = matrix[0][n - 1] for i in range(n): # Check if main diagonal elements are the same if matrix[i][i] != main_diagonal_value: return False # Check if anti-diagonal elements are the same if matrix[i][n - i - 1] != anti_diagonal_value: return False return True # Test the function with an example matrix = [[1, 2, 3], [4, 1, 2], [3, 4, 1]] print(check_diagonals(matrix)) # Output: True