Python "If max number of steps is exceeded, break the loop"

Python "If max number of steps is exceeded, break the loop"

我正在编写一个(非常复杂且不雅)Python 代码以通过蛮力对图形进行 3 色着色,并且在我的主要代码块中我试图包含一个声明说"if the max number of runs through the loop exceeds (some arbitrary number), break out of the first (while a in range(0,len(vertices))) loop"。

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。)

你有两个循环

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

向 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