Write a program to check if the given matrix is a magic square or not
Question
Write a program to check if the given matrix is a magic square or not
Solution
Sure, here is a Python program that checks if a given matrix is a magic square or not:
def is_magic_square(matrix):
# Calculate the sum of the first row
sum_row = sum(matrix[0])
# Check the sum of each row
for row in matrix:
if sum(row) != sum_row:
return False
# Check the sum of each column
for col in zip(*matrix):
if sum(col) != sum_row:
return False
# Check the sum of the main diagonal
if sum(matrix[i][i] for i in range(len(matrix))) != sum_row:
return False
# Check the sum of the secondary diagonal
if sum(matrix[i][len(matrix)-i-1] for i in range(len(matrix))) != sum_row:
return False
return True
# Test the function
matrix = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
print(is_magic_square(matrix)) # Output: True
This program works by first calculating the sum of the first row of the matrix. It then checks if the sum of each row, each column, the main diagonal, and the secondary diagonal all equal to this sum. If they do, the matrix is a magic square. If not, the matrix is not a magic square.
Similar Questions
To implement a magic square, we use the concept of matrices. Select all the statements that are True in this context. One possible Implementation of matrices is through nested lists in Python. NumPy is one of the standard libraries associated with implementing matrices. Implementation of matrices is only through lists in Python. None of the above
Write a function that computes the square value of all integers of a matrix.Prototype: def square_matrix_simple(matrix=[]):matrix is a 2 dimensional arrayReturns a new matrix:Same size as matrixEach value should be the square of the value of the inputInitial matrix should not be modifiedYou are not allowed to import any moduleYou are allowed to use regular loops, map, etc.
A 3 × 3 magic square is a 3 × 3 rectangular array of positive integers, such that the sum of the 3 numbers in any row, any column or any of the two major diagonals, is the same. Find x in the following magic square.
Select the correct statements regarding Magic Square: Magic Square of Order 1 is Trivial Sum of 2 magic squares is a magic square Magic Square of Order 2 is not possible The magic constant (the sum of row/columns/diagonal elements) for a 7*7 possible magic square is 260
Write a C program that calculates the sum of both diagonals in a square matrix. Implement a function that takes a square matrix and its size as input and returns the sum of the main diagonal and anti-diagonal elements.Input3 31 2 3 4 5 6 7 8 9
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.