2012-07-16 84 views
1

我试图解决这个问题:CodeEvalPython:奇怪的循环行为

这个问题需要我通过XY坐标中可能的点候选列表。然后,如果他们满足要求,我将它们添加到“确认”列表,然后将周围的点添加到“tosearch”列表。然而,这并不表现我所期望的行为方式。

示例代码:

Starting point 
tosearch=[[0,0]] 

for point in tosearch: 

    if conditions filled: 
     confirmed.append(point) 
     #Basically Im trying to add (x,y-1) etc. to the tosearct list 
     tosearch.append([point[0],point[1]-1]) #1 
     tosearch.append([point[0]+1,point[1]]) #2 
     tosearch.append([point[0]-1,point[1]-1])#3 
     tosearch.append([point[0],point[1]+1]) #4 
     tosearch.remove(point) 
else: 
    tosearch.remove(point) 

这似乎导致总是忽略了附加的一半。所以在这种情况下,#1和#3被忽略。如果我只剩下1个& 2,那么只有2个会执行。我不明白它...

也许问题是其他地方所以这里是整个代码: Pastebin

+2

您正在迭代列表,而您正在修改它。不要这样做。 – 2012-07-16 18:54:27

回答

5

你修改集合在遍历它。
2个选择:

  1. 副本列表,重复拷贝,并改变原来的。
  2. 记录需要进行的更改,并在迭代之后完成所有更改。
0

问题是你正在修改tosearch在迭代tosearch循环的主体。由于tosearch正在更改,因此无法可靠地进行迭代。

你可能根本不需要迭代。只需使用一个while循环:

searched = set() # if you need to keep track of searched items 
tosearch = [(0,0)] #use tuples so you can put them in a set 
confirmed = [] 

while tosearch: 
    point = tosearch.pop() 
    searched.add(point) # if you need to keep track 
    if CONDITIONS_MET: 
     confirmed.append(point) 
     # tosearch.append() ....