0

I'm having a little bit of trouble writing a recursive permutation function for solving Magic Squares. For this function, I'm not allowed to use two-dimensional arrays, only lists. Below is what I have currently:

def permute(size):
    magicSquare = []
    for value in permute(size**2):
        for pos in range(size**2 + 1):
            magicSquare.append(value)
    return magicSquare

size is defined by the user through command-line argument.

I'm slightly confused if the function written above accomplishes the task of permuting the values.

false
  • 10,264
  • 13
  • 101
  • 209
tuffbunnies9
  • 9
  • 1
  • 2
  • 1
    Do you want to find a magic square by iterating over all possible permutations of {1, 2, ..., n**2} ? If so, you should look into itertools.permutations() for getting all the permutations without implementing a recursive function yourself... – thesamet Dec 12 '11 at 05:01

2 Answers2

5

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.

David H. Clements
  • 3,590
  • 2
  • 24
  • 26
0

Here is a simple method for checking magic square or not.

Note: please try by using 3*3 grid.

def magic():
    print "maximam 9 values"
    a=[]
    for i in range(3):
        a.append([])
        for j in range(3):
            a[i].append(input('Enter the values'))
    print a
    l1= a[0][0]+a[1][0]+a[2][0]
    l2=a[0][1]+a[1][1]+a[2][1]
    l3=a[0][2]+a[1][2]+a[2][2]
    r1=sum(a[0])
    r2=sum(a[1])
    r3=sum(a[2])
    if l1 == l2 == l3 == r1 == r2 == r3:
        print a,"Its magic square"
    else:
        print a,"not magic square"
magic()
abi
  • 1
  • 2