Last active
July 11, 2024 18:45
-
-
Save beatorizu/00a6036f5055fd4ae5eb59cde8422bcb to your computer and use it in GitHub Desktop.
Generate all 3x3 magic squares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
magic_constant = 15 | |
def is_magic_square(square): | |
line = [column for row in square for column in row] | |
if len(line) != len(set(line)): | |
return False | |
for row in square: | |
if sum(row) != magic_constant: | |
return False | |
for column in zip(*square): | |
if sum(column) != magic_constant: | |
return False | |
if sum([square[i][j] for i,j in zip(range(3), range(3))]) != magic_constant: | |
return False | |
if sum([square[i][j] for i,j in zip(range(3), range(2, -1, -1))]) != magic_constant: | |
return False | |
return True | |
squares = [s for s in permutations([p for p in permutations(range(1, 10), 3) if sum(p) == magic_constant], 3) if is_magic_square(s)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment