How to check whether a matrix is a magic square or not in Python

2 Answers

0 votes
# Function to check if the matrix is a magic square
def is_magic_square(matrix):
    size = len(matrix)

    sum_diagonal1 = 0
    sum_diagonal2 = 0

    # Calculate the sum of the primary diagonal
    for i in range(size):
        sum_diagonal1 += matrix[i][i]

    # Calculate the sum of the secondary diagonal
    for i in range(size):
        sum_diagonal2 += matrix[i][size - i - 1]

    # If the two diagonals don't have the same sum, it's not a magic square
    if sum_diagonal1 != sum_diagonal2:
        return False

    # Check sums of each row and column
    for i in range(size):
        sum_row = 0
        sum_col = 0

        for j in range(size):
            sum_row += matrix[i][j]   # Sum of the current row
            sum_col += matrix[j][i]   # Sum of the current column

        # If any row or column sum is not equal to the diagonal sum, it's not a magic square
        if sum_row != sum_diagonal1 or sum_col != sum_diagonal1:
            return False

    # If all checks pass, it's a magic square
    return True


matrix = [
    [8, 3, 4],
    [1, 5, 9],
    [6, 7, 2]
]

if is_magic_square(matrix):
    print("The given matrix is a magic square.")
else:
    print("The given matrix is NOT a magic square.")



"""
run:

The given matrix is a magic square.

"""

 



answered Sep 30 by avibootz
0 votes
def is_magic_square(matrix):
    size = len(matrix)

    # Calculate the sum of the primary and secondary diagonals
    diag1 = sum(matrix[i][i] for i in range(size))
    diag2 = sum(matrix[i][size - i - 1] for i in range(size))

    # If diagonals differ, it's not a magic square
    if diag1 != diag2:
        return False

    # Check each row and column sum
    for i in range(size):
        row_sum = sum(matrix[i])
        col_sum = sum(row[i] for row in matrix)

        if row_sum != diag1 or col_sum != diag1:
            return False

    return True


matrix = [
    [8, 3, 4],
    [1, 5, 9],
    [6, 7, 2]
]

result = "magic square" if is_magic_square(matrix) else "NOT a magic square"

print(f"The given matrix is a {result}.")



'''
run:

The given matrix is a magic square.

'''

 



answered Sep 30 by avibootz
...