Programmin-in-Python

Solving Magic Square

Oct 26th, 2021
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. from random import shuffle
  2.  
  3. def colsCheck(MS):
  4.     if (MS[0][0]+MS[1][0]+MS[2][0] == 15) and (MS[0][1]+MS[1][1]+MS[2][1] == 15) and (MS[0][2]+MS[1][2]+MS[2][2] == 15):
  5.         return True
  6.     else:
  7.         return False
  8.  
  9. def diagCheck(MS):
  10.     if (MS[0][0]+MS[1][1]+MS[2][2] == 15) and (MS[0][2]+MS[1][1]+MS[2][0] == 15):
  11.         return True
  12.     else:
  13.         return False
  14.  
  15. def rowsCheck(MS):
  16.     if (sum(MS[0]) == 15) and (sum(MS[1]) == 15) and (sum(MS[2]) == 15):
  17.         return True
  18.     else:
  19.         return False
  20.  
  21. nos = [i for i in range(1, 10)]
  22. MS = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
  23.  
  24. while True:
  25.     for i in MS:
  26.         for j in range(len(i)):
  27.             shuffle(nos)
  28.             i[j] = nos.pop()
  29.  
  30.     if colsCheck(MS) and rowsCheck(MS) and diagCheck(MS):
  31.         for i in MS:
  32.             for j in i:
  33.                 print(f"{j} ", end="")
  34.             print()
  35.  
  36.         break
  37.     else:
  38.         nos = [i for i in range(1, 10)]
  39.         MS = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Advertisement
Add Comment
Please, Sign In to add comment