使用的是De la Loubère方法(也叫Siamese method)
#!/usr/bin/env python3
def magic_square(n):
'''De la Loubere's solution for n-odd magic square'''
square=[([0]*n) for i in range(n)]
mid=n//2
square[0][mid]=1
count=1
i=n-1 # i-th row
j=mid+1 # j-th column
while count<n*n:
count+=1
square[i][j]=count
i=(i-1)%n
j=(j+1)%n
if square[i][j]!=0:
i=(i+2)%n
j=(j-1)%n
return square
if __name__=='__main__':
n=int(input('input an odd integer:\n'))
square=magic_square(n)
for i in range(n):
print(square[i])
网友评论