In: Computer Science
Python:
Lo Shu Magic Square
The Lo Shu Magic Square is a grid with 3 rows and 3 columns, shown in figures below. 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. This is shown in Figure B.
In a program you can stimulate 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. Test the function in a program.
Figure A
4 |
9 |
2 |
3 |
5 |
7 |
8 |
1 |
6 |
Figure B
4 |
9 |
2 |
3 |
5 |
7 |
8 |
1 |
6 |
PYTHON CODE
# function to add a row for the given index
def sumRow(m,index):
# decrement by 1 , since index starts at
zero
index=index-1
# variable to hold the sum of values in a
row
total=0
try:
# loop through the
list
for i in
range(len(m)):
# adding every value in the inner list
for j in range(len(m[i])):
if i==index:
total+=m[i][j]
except:
print('Index Error')
# returning the total
return total
def sumCol(m,col):
# decrement by 1 , since index starts at
zero
column=col-1
# variable to hold the sum of values in a
row
total=0
try:
# loop through the
list
for i in
range(len(m)):
# adding every value in the inner list
for j,v in enumerate(m[i]):
if j==column:
total+=v
except:
print('Index Error')
# returning the total
return total
def sumdiagonal(m):
d1=m[0][0]+m[1][1]+m[2][2]
d2=m[0][2]+m[1][1]+m[2][0]
return (d1,d2)
def main(m):
# calling the sumRow() for row 1
s=sumRow(m,1)
# calling the sumRow() for row 1
r=sumRow(m,2)
# calling the sumRow() for row 1
t=sumRow(m,3)
c1=sumCol(m,1)
c2=sumCol(m,2)
c3=sumCol(m,3)
d1,d2=sumdiagonal(m)
if s == r == t == c1 == c2 == c3 == d1
==d2:
print('The given list is
Lo Shu Magic Square')
else:
print('The given list is
not a Lo Shu Magic Square')
# testing
if __name__=="__main__":
m=[[4,9,2],[3,5,7],[8,1,6]]
main(m)
m=[[1,2,3],[4,5,6],[7,8,9]]
main(m)
SCREENSHOT FOR OUTPUT