我的代码部分被跳过(python 3)

时间:2015-10-08 00:21:02

标签: python python-3.x magic-square

我的程序应该检查矩阵是否是魔方。但它跳过“添加对角线”并检查表中是否所有数字(1-16)。

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()

1 个答案:

答案 0 :(得分:0)

由于你的if语句包含多个需要全部为真的条件,所以只要一个为假,它就会移到else上。

当您的输入有效时,将运行所有功能和检查。但是,当您的输入不是幻方时,totSumRowsColumns将返回false并停止检查。