It wouldn't appear to and in fact should basically never terminate the way it is currently written.
An easy way to start thinking about this problem is that a magic square can be represented by a list of size n**2
, so a 3x3 magic square can be represented by a 9-length list. Since it is a magic square, you then need to permute over the values range(1,n+1)
, e.g., for a 3x3:
1 2 3
4 5 6
7 8 9
Check to see if this is a magic square (it isn't since the rows don't sum to the same value) and if it is, add it to your magic squares list. Either way, try the next permutation:
1 2 3
4 5 6
7 9 8
…until you are out of permutations. This is, of course, a non-optimal route because the trouble row (1, 2, 3) still won't sum to 15, so there is clear room for optimization and easily discarding possibilities that won't work.
An easy tool to either check your work or do the permutation piece for you is itertools.permutations
. Which will create a generator that will yield each additional permutation until there aren't any more.
Note that for anything beyond a trivial square size you are going to exceed the maximum recursion limit if you try to make another recursive call each time using this method. You'll need to find a way to manage that situation once size=3
. There are a couple of ways to handle that of varying degrees of complexity, depending on what exactly you are trying to do.