A n x n matrix that is filled with the numbers 1, 2, 3, …, n² is a magic square if the sum

Question:

Magic Square (Python3)

n x n matrix that is filled with the numbers 1, 2, 3, …, n² is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.

Implement the following algorithm to construct the magic n-by-n squares. This algorithm works only if n is odd.

Place a 1 in the middle of the bottom row.

After k has been placed in the (i, j) square, place k+1 into the square to the right and down, wrapping around the borders.

However, if the square to the right and down has already been filled, or if you are in the lower right corner, then you must move to the square straight up (from the last square that you were on) instead.

Skeleton:
# Populate a 2-D list with numbers from 1 to n2
def make_square ( n ):

# Print the magic square in a neat format where the numbers
# are right justified
def print_square ( magic_square ):

# Check that the 2-D list generated is indeed a magic square
def check_square ( magic_square ):

def main():
  # Prompt the user to enter an odd number 3 or greater

  # Check the user input

  # Create the magic square

  # Print the magic square

  # Verify that it is a magic square

main()

In your function main() you will prompt the user to enter an odd number. You must check that the input is a positive odd number greater than or equal to 3. If it is not, you will prompt the user to re-enter the number and check again and again.

Then you will create a 2-D list representing the Magic Square. You will then print out the magic square in a neat format by calling the function print_square(). In the function print_square() you MUST use print with formatting.

You will then call the function check_square(). This function checks that the sum of all the rows have the same value and prints out that sum. It checks that the sum of all the columns have the same value and prints out that sum. It sums the two main diagonals and prints out the sum. For a magic square of size n, the sum is n * (n2 + 1) / 2.

This is a sample of what the program will output:

Please enter an odd number: 5

Here is a 5 x 5 magic square:

11  18  25   2   9
10  12  19  21   3
 4   6  13  20  22
23   5   7  14  16
17  24   1   8  15

Sum of row = 65
Sum of column = 65
Sum diagonal (UL to LR) = 65
Sum diagonal (UR to LL) = 65

Answer:

def make_square ( n ):
magic_square = [[0 for x in range(n)]for y in range(n)]
i = n/2
j = n-1

# Fill the magic square by placing values
num = 1
while num <= (n*n):
if i == -1 and j == n: # third condition
j = n-2
i = 0
else:
# next number goes out of right side of square
if j == n:
j = 0
# next number goes out of upper side
if i < 0:
i = n-1
# print(magicSquare)
if magic_square[int(i)][int(j)]: # 2nd condition
j = j-2
i = i+1
continue
else:
magic_square[int(i)][int(j)] = num
num = num+1

j = j+1
i = i-1 #1st condition
return magic_square

def print_square ( magic_square ):

for i in range(0,len(magic_square)):
for j in range(0,len(magic_square)):
print(' ',magic_square[i][j],end='')
print()


# Check that the 2-D list generated is indeed a magic square
def check_square (magic_square):
iSize=len(magic_square)
sum_list=[]
#vertical
for col in range(iSize):
sum_list.append(sum(row[col] for row in magic_square))
print("vertical Sum:")
for i in sum_list:
print(i,end=' ')
#Horizontal
print()
sum_list=[]
sum_list.extend([sum (lines) for lines in magic_square])
print("horizontal Sum:")
for i in sum_list:
print(i,end=' ')
#Diagonals
print()
sum_list=[]
dlResult = 0
for i in range(0,iSize):
dlResult +=magic_square[i][i]
sum_list.append(dlResult)  
print("Diagonal1 Sum:")
for i in sum_list:
print(i,end=' ')
sum_list=[]
drResult = 0
print()
for i in range(iSize-1,-1,-1):
drResult +=magic_square[i][i]
sum_list.append(drResult)
print("Diagonal2 Sum:")
for i in sum_list:
print(i,end=' ')
  

def main():
# Prompt the user to enter an odd number 3 or greater
userInput=input("Enter odd number: ")
while True:
if int(userInput)>=3 and int(userInput)%2!=0:
break
else:
print("Please enter valid number")
userInput=input("Enter odd number: ")

magicSquare=make_square(int(userInput))
print(len(magicSquare))
# print(make_square(int(userInput)))
print_square(magicSquare)
check_square(magicSquare)


main()

Leave a Comment

Your email address will not be published. Required fields are marked *