2012-03-11 36 views
0

我編寫了下面的代碼,我期待這樣,當第一個循環結束並且不返回False時,流程會在第二個while循環之後進行。但是,流程會跳過第二個while循環並簡單地返回True。這是爲什麼?我怎樣才能解決這個問題,使第一個while循環轉到第二個while循環之後的流程?爲什麼在Python中兩個while循環(不在另一個循環中)不起作用?

square = [[1,2,3,4],[4,3,1,4],[3,1,2,4],[2,4,4,3]] 
# this is an auxiliary function 
def getSum(lis): 
sum = 0 
for e in lis:   
    sum = sum + e 
return sum 

# here is where the problem is 
def check_game(square): 
standardSum = getSum(range(1, len(square)+1))  

while square: #this is the first while loop 
    row = square.pop() 
    print row, 'row', 'sum of row=', getSum(row) 
    if standardSum != getSum(row): 
     return False 
m = 0 
while m < len(square): # the second while loop, which the flow skips 
    n = 0 
    col = [] 
    while n < len(square): 
     col.append(square[n][m]) 
     n = n + 1 
    print col, 'column' 
    if standardSum != getSum(col): 
     print standardSum, ' and sum of col =', getSum(col) 
     return False    
    m = m + 1 
return True 
+2

檢查壓痕這裏符合您的實際代碼 – 2012-03-11 17:51:48

+0

+1 @AramKocharyan:既不的while循環實際上是check_game功能可按內部。 – 2012-03-11 18:02:32

+0

是的,我粘貼錯了,但在我的.py文件中它是正確的縮進。謝謝,亞蘭。 – craftApprentice 2012-03-11 18:08:37

回答

5

第一個循環僅在square中沒有剩餘項目時才終止。第一個循環後,len(square)將爲0,因此第二個循環m < len(square)的輸入條件將爲False

+0

是的,確切!我沒有得到它,因爲.pop()減少了正方形元素的數量。 – craftApprentice 2012-03-11 18:09:33

+1

@ Pythonista's Apprentice:確保你在[katriealalex'answer](http://stackoverflow.com/a/9657676/279627)中學習代碼,該代碼展示瞭如何使用更具表現力,可讀性更好的方式編寫函數簡潔的態度。試着理解這些代碼,你可能會學到很多關於Python的知識! – 2012-03-12 00:39:04

1

while square:將在square爲空時終止;它遵循len(square) == 0,因此當m=0m < len(square)評估爲假。

+0

是的,確切!我沒有得到它,因爲.pop()減少了正方形元素的數量。非常感謝你們! – craftApprentice 2012-03-11 18:10:42

0

你知道你計劃迭代多少次,因爲你檢查一個長度和一個增量變量。改爲使用for循環,因爲它可以讓您初始化增量並在同一行上調整每個循環。這將避免將來導致無限循環的問題(儘管這裏不是這個問題,我認爲它指出相關)。

+0

謝謝你的明智建議。 – craftApprentice 2012-03-11 18:11:21

1

square.pop()square返回一行和刪除行,因此len(square)是在第二循環中的零。

還有一個內置函數sum,它和你的getSum函數做的功能相同。

+0

是的,確切!我沒有得到它,因爲.pop()減少了正方形元素的數量。 – craftApprentice 2012-03-11 18:10:23

0

你可以通過這個替換你的第一個,同時避免你的錯誤:

for row in square: 
    print row, 'row', 'sum of row=', getSum(row) 
    if standardSum != getSum(row): 
    return False 
2

僅供參考你的代碼是很(非常非常)未地道的Python - 它寫了不太像C.

這裏的重寫更像是Python寫的。

square = [[1,2,3,4],[4,3,1,4],[3,1,2,4],[2,4,4,3]] 
transpose = lambda i: zip(*i) 

def is_magic(square): 
    n = len(square) 
    s = n*(n+1)/2 

    return all(sum(row) == s for row in square) and \ 
      all(sum(col) == s for col in transpose(square)) 

您不妨看看numpy,其是用於處理矩陣的Python模塊。有了它:

def is_magic(square): 
    n = len(square) 
    s = n*(n+1)/2 

    return all(m.sum(0) == s) and all(m.sum(1) == s) 
+0

嗯,我想了解這個代碼...我已經讀了5次纔得到一個想法...但它不適合我。非常感謝Katrielalex爲這個美麗的代碼! – craftApprentice 2012-03-17 03:15:11

+0

@ Pythonista's Apprentice無後顧之憂。你應該首先圍繞[list comprehensions](https://en.wikipedia.org/wiki/List_comprehension#Python)。 「轉置」只是一個竅門。 – katrielalex 2012-03-17 11:55:45

相關問題