In: Computer Science
Python programming
The Lo Shu Magic Square is a grid with 3 rows and 3 columns, shown in figure. The Lo Shu Magic Square has the following properties:
The grid contains the numbers 1 through 9 exactly.
The sum of each row, each column, and each diagonal all add up to the same number as shown in figure.
In a program you can simulate a magic square using a two-dimensional list. Write a function that accepts a two-dimensional list as an argument and determines whether the list is a Lo Shu Magic Square. Tes the function in a program.
4 | 9 | 2 |
3 | 5 | 7 |
8 | 1 | 6 |
def checkLoShuMagicSquare(list):
COLUMNS = 3 # initialize column for 3*3 square
for row in list: #looping the list
for col in range (COLUMNS):
if sum(row) == sum (list[col][col] for col in range(COLUMNS)):
#comparing the sum
if sum(row)== sum(row[col] for row in list): #comparing the
sum
answer_output = str('This is a Lo Shu Magic Square')
else:
answer_output = str('This is not a Lo Shu Magic Square')
print(answer_output) #print the output
def main():
list = [[4,9,2], [3, 5, 7], [8,1,6]] #intialize alist
checkLoShuMagicSquare(list) #callig the function
main()
-------------------------------------------------output-----------------------------------------------------------
This is a Lo Shu Magic Square