Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4, An n × n matrix that is filled with the numbers 1, 2, 3, ,n2 is a magic squar

ID: 3598294 • Letter: 4

Question

4, An n × n matrix that is filled with the numbers 1, 2, 3, ,n2 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. Write a program that reads in 16 values from a file containing each row of 4 values in each line, and tests whether they form a magic square when put into a 4 × 4 table as a list of lists. You need to test two features: (a) Does each of the numbers 1,2,... , 16 occur in the the file? (b) When the numbers are put into a square, are the sums of the rows, columns and diagonals equal to each other?

Explanation / Answer

import sys

filename = input("Enter a file name: ")

magic_square = []
with open(filename) as fh:
for line in fh:
magic_square.append([int(x) for x in line.split()])

boolean_magic = [0]*16

for row in magic_square:
for cell in row:
boolean_magic[cell-1] = 1

should_continue = True
for cell in boolean_magic:
if cell == 0:
print("Not a magic square")
sys.exit(1)
row_sum = sum(magic_square[0])
for row in magic_square:
if sum(row) != row_sum:
print("Not a magic square")
sys.exit(1)

for j in range(len(magic_square[0])):
col_sum = 0
for i in range(len(magic_square)):
col_sum += magic_square[i][j]
if col_sum != row_sum:
print("Not a magic square")
sys.exit(0)
front_diaognal_sum = 0
back_diaognal_sum = 0
for i in range(len(magic_square)):
front_diaognal_sum += magic_square[i][i]
back_diaognal_sum += magic_square[len(magic_square) - i - 1][len(magic_square) - i - 1]

if back_diaognal_sum != front_diaognal_sum or back_diaognal_sum != row_sum:
print("Not a magic square")
sys.exit(0)

print("Magic square")

# copy pastable version: https://paste.ee/p/m4pmK

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote