pythonpython-3.xmatrixcomputer-sciencemagic-square

How do I create a magic square matrix using python


A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the diagonal of the matrix remain same

This code is working only for odd numbers but not even numbers.

here's my code that i tried but it didn't work `

def matrix(n): 
    m = [[0 for x in range(n)] 
                      for y in range(n)]
    i = n / 2
    j = n - 1
    num = 1
    while num <= (n * n): 
        if i == -1 and j == n:
            j = n - 2
            i = 0
        else:
            if j == n: 
                j = 0 
            if i < 0: 
                i = n - 1
        if m[int(i)][int(j)]:
            j = j - 2
            i = i + 1
            continue
        else: 
            m[int(i)][int(j)] = num 
            num = num + 1
        j = j + 1
        i = i - 1
    print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n") 
    for i in range(0, n): 
        for j in range(0, n): 
            print('%2d ' % (m[i][j]),end = '') 
            if j == n - 1:  
                print()
n=int(input("Number of rows of matrix:"))
matrix(n)

`


Solution

  • def matrix(n): 
    m = [[0 for x in range(n)] 
                      for y in range(n)]
    i = n / 2
    j = n - 1
    num = 1
    while num <= (n * n): 
        if i == -1 and j == n:
            j = n - 2
            i = 0
        else:
            if j == n: 
                j = 0 
            if i < 0: 
                i = n - 1
        if m[int(i)][int(j)]:
            j = j - 2
            i = i + 1
            continue
        else: 
            m[int(i)][int(j)] = num 
            num = num + 1
        j = j + 1
        i = i - 1
    print ("Sum of eggs in each row or column and diagonal ",n * (n * n + 1) / 2, "\n") 
    for i in range(0, n): 
        for j in range(0, n): 
            print('%2d ' % (m[i][j]),end = '') 
            if j == n - 1:  
                print()
    

    n=int(input("Number of rows of matrix:")) matrix(n)