1

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!!!!!!!

clovis
  • 325
  • 2
  • 3
  • 13
  • How many elements does `msq` have? Print `len(msq)`, and you will see. What does `[[.....]]` do? – cdarke Mar 23 '17 at 16:58
  • @cdarke in this case it should have 3 lists within a bigger list, since 3 is n. And m = [[0 for _ in range(n)] for _ in range(n)] is just supposed to create a 2d array – clovis Mar 23 '17 at 17:04
  • But your code does not do that, you have a `]` in the wrong position. Also, `col` must be converted to an `int`..... – cdarke Mar 23 '17 at 17:07
  • Whats `M`? As in `while v != M:` – cdarke Mar 23 '17 at 17:08
  • 1
    Even when you fix all those, you will break with `RecursionError` because there is no return from the function that is not recursive. – cdarke Mar 23 '17 at 17:10
  • oh shoot, M is the magic constant. Ah okay, how should I go about fixing that? – clovis Mar 23 '17 at 17:23
  • @cdarke, oh okay I fixed the placement of the brackets, and now it's `list indices must be integers or slices, not float`, so I see what you mean in that sense – clovis Mar 23 '17 at 17:26
  • Why are you calling the function again in the `return`? Do you need recursion? I would have thought you just `return msq`. – cdarke Mar 23 '17 at 19:25

0 Answers0