my program is supposed to check whether a matrix is a magic square. however it skips "adding the diagonals" and checking whether all the number (1-16) are in the table.
ROWS=4
COLUMNS=4
def main():
tbl=[]
numChecktbl=[]
for i in range (ROWS):
tbl.append([])
for j in range (COLUMNS):
userinput=int(input("Enter a value for location (%d,%d): " %(i,j)))
tbl[i].append(userinput)
numChecktbl.append(userinput)
for i in range(ROWS):
for j in range(COLUMNS):
print("%3d" %tbl[i][j], end='')
print()
if (totSumRowsColumns(ROWS,COLUMNS,tbl)and totSumDiagonals(ROWS,COLUMNS,tbl)
and numInMatrix(numChecktbl)):
print("It is a magic square")
else:
print("It is not a magic square")
def totSumRowsColumns(ROWS,COLUMNS,tbl):
for i in range (ROWS):
totalrow=0
totalColumn=0
for j in range (COLUMNS):
totalColumn+=tbl[j][i]
totalrow=totalrow+tbl[i][j]
if (totalrow != 34!=totalColumn):
return False
return True
def totSumDiagonals(ROWS,COLUMNS,tbl):
totDiag1=0
totDiag2=0
for i in range (ROWS):
for j in range (COLUMNS):
totDiag1=tbl[0][3]+tbl[1][2]+tbl[2][1]+tbl[3][0]
if i==j:
totDiag2+=tbl[i][j]
if (totDiag1!=totDiag2!=34):
return False
return True
def numInMatrix(numChecktbl):
for i in range(1,17):
if i not in numChecktbl:
return False
return True
main()
Since your if statement contains multiple conditions that need to all be true, as soon as one is false it moves onto the else.
When your input is valid, all the functions and checks run. However, when your input is not a magic square, totSumRowsColumns
returns false and the checks are stopped.