from math import log

class MagicSquare :
    def __init__(self, L) :
        self.dim = int( len(L)**0.5 )
        self.matrix = [ [ L[i+j*3] for i in range(self.dim) ] for j in range(self.dim) ]

    def __str__(self) :
        out = ''
        p = 1
        w = int( log( self.dim , 10) ) + 1 # nombre de chiffres dans self.dim pour le formattage de l'affichage
        formatage = '%' + str(w+3) + 'd'
        for row in self.matrix:
            for coef in row:
                out += str( formatage % ( coef ) )
                if p % self.dim == 0:
                    out += '\n'
                p += 1
        return out
    
    def isMagic(self):
        # on vérifie d'abord si tous les nombres sont uniques
        liste_nombres = []
        for row in self.matrix:
            for coef in row:
                if coef not in liste_nombres:
                    liste_nombres.append( coef )
                else:
                    return False
        
        somme_theorique = self.dim * (self.dim**2 + 1) // 2
        
        # somme de chaque ligne
        for row in self.matrix:
            somme = 0
            for coef in row:
                somme += coef
            if somme != somme_theorique:
                return False
        
        # somme de chaque colonne
        for column in range(self.dim):
            somme = 0
            for row in range(self.dim):
                somme += self.matrix[row][column]
            if somme != somme_theorique:
                return False
            
        # somme des diagonales
        somme1 , somme2 = 0 , 0
        for i in range(self.dim):
            somme1 += self.matrix[i][i]
            somme2 += self.matrix[i][self.dim-1-i]
        if somme1 != somme_theorique or somme2 != somme_theorique:
            return False
        
        return True
        
    
"""   
square = MagicSquare ( [ 1,9,2,3,5,7,8,1,6 ] )
print( square )
print( square.isMagic() )
"""
def all_squares():
    for a1 in range(1,10):
        for a2 in range(1,10):
            for a3 in range(1,10):
                for b1 in range(1,10):
                    somme = a1 + a2 + a3
                    c1 = somme - a1 - b1
                    b2 = somme - a3 - c1
                    b3 = somme - b1 - b2
                    c2 = somme - a2 - b2
                    c3 = somme - c1 - c2
                    M = MagicSquare( [a1,a2,a3,b1,b2,b3,c1,c2,c3] )
                    if M.isMagic() and 0 < b2 < 10 and 0 < b3 < 10 and 0 < c1 < 10 and 0 < c2 < 10 and 0 < c3 < 10 :
                        print(M)
                        print("---------------")
                        
all_squares()
