def magic_square(n):
magicSquare = []
for i in range(n):
l=[]
for j in range(n):
l.append(0)
magicSquare.append(l)
i=n//2
j=n-1
num = n*n
count = 1
while(count<=num):
if(i==-1 and j==n):
j = n-2
i = 0
else:
if(j==n):
j=0
if(i<0):
i=n-1
if(magicSquare[i][j]!=0): # here iam getting error sign as(list index out of range) . how to rectify this ???
i=i+1
j=j-2
continue
else:
magicSquare[i][j]=count
count+=1
i=i-1
j=j+1
for i in range(n):
for j in range(n):
print(magicSquare[i][j],end=" ")
print()
magic_square(3)
Result as:
runfile('D:/01The Joy Of Computing Using Python/Spyder/Magic_square.py', wdir='D:/01The Joy Of Computing Using Python/Spyder') Traceback (most recent call last):
File "", line 1, in runfile('D:/01The Joy Of Computing Using Python/Spyder/Magic_square.py', wdir='D:/01The Joy Of Computing Using Python/Spyder')
File "C:\Users\intel\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile execfile(filename, namespace)
File "C:\Users\intel\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace)
File "D:/01The Joy Of Computing Using Python/Spyder/Magic_square.py", line 56, in magic_square(3)
File "D:/01The Joy Of Computing Using Python/Spyder/Magic_square.py", line 41, in magic_square if(magicSquare[i][j]!=0):
IndexError: list index out of range