Tuesday, April 20, 2021

Magic Square - Python Code

Write a CODE in Python to make a Magic Sqaure

'''
6 1 8
7 5 3
2 9 4
'''
M=[[0,0,0],[0,0,0],[0,0,0]]

for i in M:
  print(i)

Start=1
R=0;C=1

# Fill in the First Number
M[R][C]=Start

# Fill in the rest of the values in Sequence 2,3,...
while True:
  TR=(R-1) if R>0 else 2
  TC=(C-1) if C>0 else 2
  if M[TR][TC]!=0:
    R=R+1
  else:
    R=TR
    C=TC
  Start+=1
  M[R][C]=Start
  if Start==9:
    break
print("-"*10)
for i in M:
  print(i)


'''
12  2  16
14 10   6
 4 18   8
'''
M=[[0,0,0],[0,0,0],[0,0,0]]

for i in M:
  print(i)

Start=2
R=0;C=1

# Fill in the First Value of the Sequence
M[R][C]=Start

# Fill in the rest of the value of the Sequence 4,6,8,...
while True:
  TR=(R-1) if R>0 else 2
  TC=(C-1) if C>0 else 2
  if M[TR][TC]!=0:
    R=R+1
  else:
    R=TR
    C=TC
  Start+=2
  M[R][C]=Start
  if Start==18:
    break
    
print("-"*10)
for i in M:
  print(i)