Created
September 17, 2016 22:48
-
-
Save maxdeliso/467eacc0b674fdd160cd5e34b5f0a115 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class MagicSquare(): | |
def __init__(self, n): | |
assert(n % 2 == 1) | |
self.n = n | |
self.matrix = list( | |
map(lambda _: | |
list(map(lambda _: 0, list(range(1, n+1)))), | |
range(1, n+1))) | |
self.__construct() | |
def __construct(self): | |
current_row = self.n // 2 + 1 | |
current_col = self.n // 2 | |
for i in range(1, self.n * self.n + 1): | |
self.matrix[current_row][current_col] = i | |
next_row = (current_row + 1) % self.n | |
next_col = (current_col + 1) % self.n | |
if(self.matrix[next_row][next_col] != 0): | |
current_row = (current_row + 2) % self.n | |
else: | |
current_row = next_row | |
current_col = next_col | |
def __str__(self): | |
return "\n".join(map(str, self.matrix)) | |
if(__name__ == '__main__'): | |
print(str(MagicSquare(7))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment