我写了下面的代码,我希望,当第一个循环结束并且没有返回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
第一个循环只在
square
中没有其他项目时终止。在第一个循环之后,len(square)
将是0
,因此第二个循环m < len(square)
的进入条件将是False
。在当},因此{}在{}时计算结果为false。在
square
为空时,while square:
将终止;接下来是{仅供参考,您的代码非常(非常非常)不是惯用的Python——它的编写更像C
这里有一个重写,它更像Python通常编写的。在
您可能希望研究一下
^{pr2}$numpy
,这是一个用于处理矩阵的Python模块。有了它:相关问题 更多 >
编程相关推荐