我想返回一个输出,它是元素中全部为零的行数。这是我的python代码,我无法确定bug在哪里。你知道吗
def find_bully_1(A):
n = len(A)
candidate = 0
count = 0
for i in range(n):
for j in range(n):
if A[i][j] == 0:
count = count + 1
if count == n:
candidate = candidate + 1
return candidate
x = [[1,1,1,1],
[0,0,0,0],
[0,0,0,0],
[0,1,0,0]]
find_bully_1(x)
The output should be 2 but it keeps return 1.
到目前为止,您的代码对所看到的每一个0都进行计数,但它应该只是对当前行中的0进行计数。要解决这个问题,需要在进入
for j in range(n):
循环之前将count
重置为零。你知道吗然而,用这种方法计算所有的零行是低效的。更好的方法是将^{} 函数与^{} 或
all
结合使用。例如:输出
FWIW,我不会费心把代码放到函数中,因为Python函数调用相对较慢,调用函数所需的代码并不比编写代码本身短多少:
在您的示例中,计数只会永远每0递增一次,并且永远不会重置
只需在for循环开始时重置计数
您可以使用
sum
:输出:
相关问题 更多 >
编程相关推荐