2012-03-11 107 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

相关问题