Reputation: 335
So I'm trying to make a function that takes an integer 'n' and returns a list of lists, and this is all in the vein of making a 'magic square' (start at 1 in the top center, then go right and up to the next, all with a 'wraparound' effect). Anyway, I feel my code is super clunky but also I can't test if it works because well it doesn't.. I get a list index out of range
message for the line msq[row][col] = v
. Here's the code:
def magicsquare(n):
msq = [[0 for c in range(n)] for r in range(n)]
row, col= n-1, (n-1)/2
M = n*(n+1)/2
v, r, c = 1,0,0
msq[row][col] = v
while v != M:
v= v+1
if row+1 >= n:
r = 0
else: r = row + 1
if (col+1) < n:
c = col + 1
else: c = 0
if msq[r][c]:
if (row+1) < n:
r = row+1
c = col
grid[r][c] = v
row = r
col = c
return magicsquare(n)
oh and the test I'm trying to pass is magicsquare(3) == magicsquare([[4, 3, 8], [9, 5, 1], [2, 7, 6]])
. Any help is appreciated, thank you!!!!!!!
Upvotes: 1
Views: 116