我正在制作一个(非常复杂且不优雅)的Python代码,通过暴力破解三色图形,在我的主要代码块中,我试图包含一个声明&# 34;如果通过循环的最大次数超过(某个任意数字),则跳出第一个(while a in range(0,len(vertices))
)循环"。
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
然而,我发现即使经过了超过100000步(我可以看到,因为我打印了步数),循环不会中断并变成无限循环,并且数字步骤继续超过100000.我应该包括另一个循环,
while steps < 100000:
而不只是在我的第一个循环中添加另一个条件?我是在犯一个语法错误,还是我的代码更深入的问题?
(完整代码可用here。)
答案 0 :(得分:1)
你有两个循环
break
所以当你for j in newdict:
时,它会打破内部循环,break
你需要为while
循环{{1}}添加另一个条件
答案 1 :(得分: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