为什么Python中两个while循环一个接一个(而不是在另一个内部)不起作用?

2024-10-02 22:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了下面的代码,我希望,当第一个循环结束并且没有返回False时,流将跟随到第二个while循环。但是,流跳过第二个while循环并返回True。为什么?如何解决这个问题,使第一个while循环之后的流转到第二个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 

Tags: thefalsetruelenreturniscolthis
3条回答

第一个循环只在square中没有其他项目时终止。在第一个循环之后,len(square)将是0,因此第二个循环m < len(square)的进入条件将是False。在

square为空时,while square:将终止;接下来是{},因此{}在{}时计算结果为false。在

仅供参考,您的代码非常(非常非常)不是惯用的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模块。有了它:

^{pr2}$

相关问题 更多 >