Check given matrix is magic square or not | Python3 program to check whether a given matrix is magic matrix or not ; Returns true if mat [ ] [ ] is magic square , else returns false . ; calculate the sum of the prime diagonal ; the secondary diagonal ; For sums of Rows ; check if every row sum is equal to prime diagonal sum ; For sums of Columns ; check if every column sum is equal to prime diagonal sum ; Driver Code
N = 3 NEW_LINE def isMagicSquare ( mat ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s = s + mat [ i ] [ i ] NEW_LINE DEDENT s2 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s2 = s2 + mat [ i ] [ N - i - 1 ] NEW_LINE DEDENT if ( s != s2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT rowSum = 0 ; NEW_LINE for j in range ( 0 , N ) : NEW_LINE INDENT rowSum += mat [ i ] [ j ] NEW_LINE DEDENT if ( rowSum != s ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT colSum = 0 NEW_LINE for j in range ( 0 , N ) : NEW_LINE INDENT colSum += mat [ j ] [ i ] NEW_LINE DEDENT if ( s != colSum ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 2 , 7 , 6 ] , [ 9 , 5 , 1 ] , [ 4 , 3 , 8 ] ] NEW_LINE if ( isMagicSquare ( mat ) ) : NEW_LINE INDENT print ( " Magic ▁ Square " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ a ▁ magic ▁ Square " ) NEW_LINE DEDENT