Skip to content

Instantly share code, notes, and snippets.

@akaban01
Created November 17, 2019 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaban01/1383ce7001edf64bd34efee7ede2c7b2 to your computer and use it in GitHub Desktop.
Save akaban01/1383ce7001edf64bd34efee7ede2c7b2 to your computer and use it in GitHub Desktop.
Takes odd number and create a magic square.
class MagicSquare:
def __init__(self, sideLength):
self.sideLength = sideLength
#1. Grid
self.grid = [[0 for x in range(sideLength)] for y in range(sideLength)]
#2.
i = 1
#3.
# current row and col for current position. Set to the middle of first row
row = 0
col = int(sideLength/2)
while(True):
#4.
self.grid[row][col] = i
#5.
if(i == sideLength*sideLength):
break
#6
if(i%sideLength == 0):
row+= 1
#handling out of bound
if(row == sideLength):
row = 0
else:
col+= 1
row-= 1
#handling out of bound
if(col == sideLength):
col = 0
if(row == -1):
row = sideLength - 1
i+= 1
def display(self):
for row in self.grid:
for col in row:
print(col, end =" ")
print()
l = int(input("Enter odd number: "))
ms = MagicSquare(l)
ms.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment