questionThe Magic Square is a grid with 3 rows and 3 columns with the following properties:
β’ The grid contains every number from 1 to 9.
β’ The sum of each row, each column, and each diagonal all add up to the same number.
This is an example of a Magic Square:
4 9 2
3 5 7
8 1 6
You can simulate a 3x3 grid using a two-dimensional list. For example, the list
corresponding to the grid above would be: [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
Write a function that accepts a two-dimensional list as an argument and
returns whether the list represents a Magic Square (either True or False).
Create a program that tests the function on the following two-dimensional lists and prints out the results each on a separate line:
[[4, 9, 2], [3, 5, 7], [8, 1, 6]]
[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[4, 9, 2], [3, 5, 5], [8, 1, 6]]
answerdef Sq_magic(inp):
#declare the size
size = len(inp[0])
#initialise the list
lst = []
#for loop for vertical angle
for c in range(size):
#append the values
lst.append(sum(r[c] for r in inp))
#set the horizontal value
lst.extend([sum (lines) for lines in inp])
#set the diagonal value
rst = 0
#for loop to find the result
for i in range(0,size):
rst +=inp[i][i]
#append the values
lst.append(rst)
d_rst = 0
#for loop to find the result
for i in range(size-1,-1,-1):
d_rst +=inp[i][i]
#append the values
lst.append(d_rst)
#check the length of the list
if len(set(lst))>1:
#return false
return False
return True
#function call that accepts two dimensional list
print(Sq_magic([[4,9,2], [3,5,7], [8,1,6]]))
print(Sq_magic([[2,7,6], [9,5,1], [4,3,8]]))
print(Sq_magic([[1,2,3], [4,5,6], [7,8,9]]))
print(Sq_magic([[4,9,2], [3,5,5], [8,1,6]]))