Hello. My instructor want me to write a magic Square code. And here is what the square is supposed to print:
11 18 25 2 9
10 12 19 21 3
4 6 13 20 22
23 5 7 14 16
17 24 1 8 15

Here is my current output.
[[16, 18, 25, 2, 9], [10, 12, 19, 0, 3], [4, 6, 13, 20, 22], [23, 5, 7, 14, 21], [17, 24, 1, 8, 15]]
I am not working on the formatting of the output right now, but was wondering why 16 prints on the top first column first row. Apparently, the code has overidden the 11 originally written for the place.
here is my code.

def magicSquare(n):
    grid = [ [ 0 for c in xrange(n) ] for r in xrange(n) ]
    row=n-1
    col=n/2
    n2=n*n
    startNum=1
    r, c= 0,0
    n2=n**2
    grid[row][col]=startNum
    while startNum != n2:
        startNum=startNum+1
        if (row + 1) <n:
            r=row+1
        else:
            r=0
        if (col+ 1) <n:
            c=col+1
        else:
            c=0
        if grid[r][c]:
            if (row+1)<n:
                r=row-1
                if grid[r][col]:
                    break
                c=col
        grid[r][c]=startNum
        row=r
        col=c
    for r in xrange(n):
        for c in xrange(n):
            print "%2d" % grid[r][c],
            print
            
    return grid

Yes, I searched the forums for the code snippets posted.

Note also that you start with zero, not one, and your zero replaces 21, and your 21 replaces 16. One problem is that you generate 26 numbers, zero through 25, with only 25 spaces to hold them. I have no other advice because "And here is what the square is supposed to print" yields this solution:
print "11 18 25 2 9"
etc. as there is nothing else that can be deduced from the question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.