gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:07 25 4
gpt4 key购买 nike

我正在编写一个(非常复杂且不优雅的)Python 代码,通过强力对图形进行 3 色处理,并且在我的主要代码块中,我试图包含一个声明,该声明表示“如果最大数量运行循环超出(某个任意数字),跳出第一个 (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 。)

最佳答案

你有两个循环

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

关于 python "If max number of steps is exceeded, break the loop",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42586668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com