An n × n matrix that is filled with the numbers 1, 2, 3, . . . , n2 is a magic s
ID: 3596462 • Letter: A
Question
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 PYTHON 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? 1 (b) When the numbers are put into a square, are the sums of the rows, columns and diagonals equal to each other?
Explanation / Answer
def check_magic_square(square):
values = [0]*16
for row in square:
for cell in row:
if cell < 1 or cell > 16 or values[cell-1] != 0:
return False
requiredSum = sum(square[0])
for row in square:
if sum(row) != requiredSum:
return False
for j in range(len(square[0])):
s = 0
for i in range(len(square)):
s += square[i][j]
if s != requiredSum:
return False
s1 = 0
s2 = 0
for i in range(len(square)):
s1 += square[i][i]
s2 += square[len(square)-i-1][len(square)-i-1]
if s1 != requiredSum or s2 != requiredSum:
return False
return True
magic = [[0]*4]*4
print(magic)
filename = input("Filename: ")
with open(filename) as fh:
i = 0
for line in filename:
vals = line.split()
for j in range(len(vals)):
magic[i][j] = int(vals[j])
i += 1
print(check_magic_square(magic))
# copy pastable code link: https://paste.ee/p/Ayccb
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.