0

我正在尝试解决一个检查任务,您必须计算给定二维数组中的岛数,其中岛定义为水平、对角线或垂直连接的一组“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]]
4

1 回答 1

3

这是因为您每次调用 .remove() 时都会在迭代列表时更改列表的大小

对于一个非常小的例子,尝试这样做:

items = [1, 2, 3, 4, 5]

for item in items:
    if item == 2:
        items.remove(item)

    print item

您会看到这打印出 1、2、4 和 5。3 去哪儿了?好吧,发生的事情是 Python 持有一个指向它迭代的列表中的位置的指针,但随后列表在该指针下方发生了变化,有点像从某人身上拉出地毯。

有一些很好的方法可以解决这个问题:您可以从长度向后循环到零,或者您可以在任何时候从索引中减去 1 remove()。你也可以做一个while循环并设置一个标志,上面写着“在这个循环中,我们发现了一些零”,然后如果那个标志为假,退出while循环。效率不是很高,但很有效。

于 2013-07-03T17:53:45.090 回答