我正在研究一個(非常複雜和不雅)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。)
您還沒有描述錯誤。你期望打破哪一個循環?你怎麼知道它確實或不休息?等等 – pvg
謝謝!我做了一些編輯。希望這更清楚。 –
您可以將'steps'條件添加到while條件中,這樣在你離開內部循環後,while將不會繼續。 break只會讓你離開內部循環。 – pvg