2017-03-03 86 views
1

我正在研究一個(非常複雜和不雅)Python代碼,通過蠻力3色圖形,並且在我的主代碼塊I' m試圖包含一個聲明,說「如果通過循環的最大運行次數超過(某些任意數量),跳出第一個(while a in range(0,len(vertices)))循環」。Python「如果超過最大步數,打破循環」

a = 0 
steps = 0 
while a in range(0,len(vertices)): 
    for j in newdict: 
     steps+=1  #count number of times it goes through the loop 
     print(steps) 
     if a>=len(vertices) or steps>=100000: 
      break  #this is where my error is occurring 

     i = vertices[a] 
     if dict1[i[0]]==dict1[i[1]] and (list(dict1.values()))!=j: #if the adjacent vertices are the same color and we have not cycled back to our original dict1, 
      dict1[i[1]]=colors[dict1[i[1]]+1] #change color of the second vertex 
      a = 0 #after a vertex is changed colors, I don't want it to keep going: I want the code to stop and reexamine from the top with this new value 
      newdict.append(list(dict1.values())) #running list of all previous dictionaries (attempted colorings): if our dictionary ever cycles through to something it already was, try again 
      check = all(dict1[i[0]] != dict1[i[1]] for i in vertices) # check all adjacent vertices are different colors 
      if not check: 
       continue 
      elif check: 
       break #at any point throughout the code, if the graph is colorable, break the loop and jump to end instead of continuing to color 
     elif dict1[i[0]]==dict1[i[1]]: #if we do eventally cycle back to our original dict1, now we'll try changing the first vertex color 
      dict1[i[0]] = colors[dict1[i[0]] + 1] 
      a = 0 
      newdict.append(list(dict1.values())) 
      check = all(dict1[i[0]] != dict1[i[1]] for i in vertices) # check all adjacent vertices are different colors 
      if not check: 
       continue 
      elif check: 
       break #at any point throughout the code, if the graph is colorable, break the loop and jump to end instead of continuing to color 
     else: 
      a+=1 

然而,我發現,即使超過10步經過(這是我所看到的,我打印的步數),循環不打破,成爲一個無限循環,而且數量步驟繼續超過100000.我應該包括另一個循環,

while steps < 100000: 

而不是隻是添加另一個條件,我的第一個循環?我是在犯一個語法錯誤還是對我的代碼更深入的問題?

(完整的代碼可以here。)

+0

您還沒有描述錯誤。你期望打破哪一個循環?你怎麼知道它確實或不休息?等等 – pvg

+0

謝謝!我做了一些編輯。希望這更清楚。 –

+0

您可以將'steps'條件添加到while條件中,這樣在你離開內部循環後,while將不會繼續。 break只會讓你離開內部循環。 – pvg

回答

1

你有兩個循環

while a in range(0,len(vertices)): # Loop 1 
    for j in newdict: # Loop 2 
     steps+=1  #count number of times it goes through the loop 
     print(steps) 
     if a>=len(vertices) or steps>=100000: 
      break  #this is where my error is occurring 

所以當你break,它打破內部循環,這是for j in newdict:你有另一個條件添加到break循環while

+1

謝謝,我完全錯過了!我在我的第一個'while'循環中包含'steps'條件,並且它工作正常。 –

0

在while語句中添加另一個條件,然後在中斷之前設置此條件。

max = False 
while a in range(0,len(vertices)) and not max: 
... 
    for j in newdict: 
     ... 
     if a>=len(vertices) or steps>=100000: 
      max = True 
      break  #this is where my error is occurring