简体   繁体   English

Python:怪异的循环行为

[英]Python: Weird for loop behavior

I'm trying to solve this: CodeEval . 我正在尝试解决此问题: CodeEval

The problem requires me to go through a list of possible candidates of points in a XY-coordinates. 这个问题要求我仔细查看XY坐标中可能的候选点列表。 Then if they fulfill the requirements I add them to a "confirmed" list and then add the surrounding points to a "tosearch" list. 然后,如果它们满足要求,则将它们添加到“已确认”列表中,然后将周围的点添加到“ tosearch”列表中。 However this does not behave at all the way I expect it to behave. 但是,这并不完全符合我期望的方式。

Example code: 示例代码:

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)

This seems to result in always ignoring half of the appends. 这似乎导致总是忽略附加内容的一半。 So in this case #1 and #3 are being ignored. 因此,在这种情况下,#1和#3被忽略。 If I left only 1&2 then only 2 would execute. 如果我只留下1&2,那么只有2个会执行。 I dont get it... 我不明白...

Maybe the problem is else where so here is the whole code: Pastebin 也许问题出在其他地方,所以这里是整个代码: Pastebin

You're modifying the collection while iterating over it. 您在迭代集合时对其进行修改。
2 options: 2种选择:

  1. copy the list, iterate the copy, and alter the original. 复制列表,迭代副本,然后更改原始文档。
  2. keep track of what changes need to be made, and make them all at after iterating. 跟踪需要进行哪些更改,并在迭代后全部进行更改。

The problem is you are modifying tosearch in the body of the loop that iterates tosearch . 问题是你要修改tosearch在迭代的循环体tosearch Since tosearch is changing, it can't be iterated reliably. 由于tosearch不断变化,因此无法可靠地对其进行迭代。

You probably don't need to iterate at all. 您可能根本不需要迭代。 Just use a while loop: 只需使用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() ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM