我试图解决一个checkio任务,其中必须计算给定二维数组中的孤岛数,其中孤岛定义为一组水平、对角或垂直连接的“1”(http://www.checkio.org/mission/task/info/calculate-islands/python-3/)。我写的代码应该首先从搜索空间中删除一个位置(我不知道我是否使用了正确的词,我对算法一无所知),如果位置中的数字是0。问题是,该代码只删除了一些编号为0的位置,而没有删除其他编号为0的位置。代码如下:
def checkio(data):
result = ''
count = 0
boo = True
searchspace = []
specificsearchspace = []
def search(y,x):
result = ''
count = 0
if data[y][x] == 0:
searchspace.remove([y,x])
if data[y][x] == 1:
specificsearchspace.extend([[y,x+1],[y+1,x-1],[y+1,x],[y+1,x+1]])
for i in specificsearchspace:
if data[i[0]][i[1]] == 0:
searchspace.remove(i)
specificsearchspace.remove(i)
if data[i[0]][i[1]] == 1:
searchspace.remove(i)
specificsearchspace.remove(i)
count += 1
search(i[0],i[1])
result += str(count) + ','
return result
for y in range(len(data)):
for x in range(len(data[y])):
searchspace.append([y,x])
print searchspace
for f in searchspace:
print search(f[0],f[1])
print searchspace
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]) == [1, 3], "1st example"
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 0, 0]]) == [5], "2nd example"
assert checkio([[0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]]) == [2, 3, 3, 4], "3rd example"
输出如下:
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
None
None
None
None
1,
None
None
None
None
None
[[0, 1], [0, 3], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [4, 0], [4, 2], [4, 4]]
这是因为每次调用.remove()时,您都在迭代列表时更改列表的大小
举个很小的例子,试着这样做:
你会看到这个打印1,2,4和5。3去哪了?好吧,发生的事情是Python持有一个指针,指向它在列表中迭代过的地方,但是列表在该指针下面发生了变化,有点像从某人下面拉出地毯。你知道吗
有几种很好的方法可以解决这个问题:可以从长度向下循环到零,也可以在每次删除()时从索引中减去1。你也可以做一个while循环,设置一个标志,上面写着“在这个循环中,我们找到了一些零”,如果这个标志为false,就退出while循环。不是很有效率,但是很有效。你知道吗
相关问题 更多 >
编程相关推荐