簡體   English   中英

為什么我的Python函數不返回結果?

[英]Why my Python function doesn't return the result?

我正在嘗試編寫一個Python函數,它可以在評估幻方時返回“True”或“False”。 幻方是一個矩陣,其行和,列總和和兩個對角線的總和是相同的。 (矩陣的一個對角線從左上角到右下角,另一個對角線從右上角到左下角。)

這是我的代碼:

def isMagic(A3):
    dim = A3.shape[0] * A3.shape[1]
    construct = np.arange(1,dim+1)
    if A3.shape[0] == A3.shape[1]:
        exist = []
        for r in range(len(A3)):
            for c in range(len(A3)):
                exist.append(A3[r,c] in construct)
        if all(exist):
            def all_same(items):
                return all(x == items[0] for x in items)
            dig_1 = sum(np.diag(A3))
            dig_2 = sum(np.diag(np.fliplr(A3)))
            dig = all_same(np.array([dig_1, dig_2]))
            column = all_same(np.sum(A3, axis = 1))
            row = all_same(np.sum(A3, axis = 0).transpose())
            if all(dig, column, row):
                return True
            else:
                return False

然而,當我嘗試在魔方之一上測試我的代碼時,該函數不會返回任何值:

test2 = np.matrix([[8, 1, 6],
              [3, 5, 7],
              [4, 9, 2]])
isMagic(test2) # True

我想知道如果是因為縮進?

對於前兩個if語句, if A3.shape[0] == A3.shape[1]並且if all(exist) ,請注意條件是否為false,否則返回任何( None )。 如果你的所有if條件都不滿足,我想你想要返回False。 然后只在函數的最后放置return False ,這樣如果未達到return True則運行:

def isMagic(A3):
    ...
    return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM