Magic Square Validation
Problem Statement
Determine if a given n x n matrix is a magic square, i.e., all rows, columns, and diagonals sum to the same number.
Solution
We will create a function is_magic_square that takes a 2D list (matrix) as input and returns a boolean indicating whether the matrix is a magic square.
Code
def is_magic_square(matrix):
"""
Validate if a given n x n matrix is a magic square.
Args:
matrix (list): A 2D list representing the matrix.
Returns:
bool: True if the matrix is a magic square, False otherwise.
"""
# Check if the matrix is square
n = len(matrix)
if any(len(row) != n for row in matrix):
return False
# Calculate the expected sum
expected_sum = sum(matrix[0])
# Check rows
for row in matrix:
if sum(row) != expected_sum:
return False
# Check columns
for col in range(n):
if sum(matrix[row][col] for row in range(n)) != expected_sum:
return False
# Check diagonals
diagonal1 = sum(matrix[i][i] for i in range(n))
diagonal2 = sum(matrix[i][n - i - 1] for i in range(n))
if diagonal1 != expected_sum or diagonal2 != expected_sum:
return False
return True
# Example usage
if __name__ == "__main__":
# Define a magic square
magic_square = [
[4, 9, 2],
[3, 5, 7],
[8, 1, 6]
]
# Define a non-magic square
non_magic_square = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(is_magic_square(magic_square)) # Output: True
print(is_magic_square(non_magic_square)) # Output: False
Explanation
The provided code defines a function is_magic_square that checks if a given matrix is a magic square. Here's a step-by-step breakdown:
- Check if the matrix is square: Verify that the matrix has the same number of rows and columns.
- Calculate the expected sum: Compute the sum of the first row, which will be used as a reference for all other rows, columns, and diagonals.
- Check rows: Iterate through each row and verify that its sum equals the expected sum.
- Check columns: Iterate through each column and verify that its sum equals the expected sum.
- Check diagonals: Compute the sums of the two diagonals and verify that they equal the expected sum.
- Return result: If all checks pass, return
True, indicating that the matrix is a magic square. Otherwise, return False.
The example usage demonstrates the function's application with a magic square and a non-magic square.