0

Is it possible to do magic squares with the Siamese/De La Loubere method without using modulo?

I would like to make odd n x n magic squares using it.

Tony Garangean
  • 97
  • 1
  • 1
  • 6

1 Answers1

0

Yes, it's possible. Written on Python 3.5:

def siamese_method(n):

    assert(n % 2 != 0), 'Square side size should be odd!'
    square = [[0 for x in range(n)] for x in range(n)]
    x = 0
    y = int((n + 1) / 2 - 1)
    square[x][y] = 1

    for i in range(2, n * n + 1):
        x_old = x
        y_old = y

        if x == 0:
            x = n - 1
        else:
            x -= 1

        if y == n - 1:
            y = 0
        else:
            y += 1

        while square[x][y] != 0:
            if x == n - 1:
                x = 0
            else:
                x = x_old + 1
            y = y_old

        square[x][y] = i

    for j in square:
        print(j)


siamese_method(3)

I've got following on output:

[8, 1, 6]
[3, 5, 7]
[4, 9, 2]
Alderven
  • 7,569
  • 5
  • 26
  • 38
  • hello, can you explain further what the line "square = [[0 for x in range(n)] for x in range(n)]" does? It wasn't taught to us to use it... I mean is there other way to not use that? – Tony Garangean Mar 05 '15 at 16:06
  • 1
    In this line creates a list containing n lists initialized to 0. In other words it is 2d array. For more info see: http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python – Alderven Mar 05 '15 at 17:44