전 (매우 복잡하고 세련되지 않은) Python 코드에서 무작위로 3 색 그래프를 만들고 있습니다. 코드의 주요 블록에 ' "루프를 통한 최대 실행 횟수 (임의의 숫자)를 초과하면 첫 번째 (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
그러나, 나는 이상 100000 단계 (내가 단계의 수를 인쇄하고 있습니다로 볼 수있는) 경과해도, 루프 수는 휴식과 무한 루프가되고,하지 않는 것을 발견 단계,
while steps < 100000:
대신 단지 내 첫 번째 루프에 다른 조건을 추가 100000 내가 다른 루프를 포함시켜야 지난 계속? 구문 오류가 있습니까? 아니면 코드에 더 많은 문제가 있습니까?
(전체 코드를 사용할 수 here입니다.)
오류를 설명하지 않았습니다. 어느 루프에서 빠져 나오기를 기대합니까? 당신은 그것이 깨닫지 못하거나 깨지지 않았 음을 어떻게 압니까? – pvg
고마워요! 나는 약간의 편집을했다. 희망적으로 그것은 더 분명하다. –
while 조건에'steps' 조건을 추가 할 수 있습니다. 그러면 while 루프는 내부 루프를 벗어난 후 계속 진행되지 않습니다. 'break'는 당신을 내부 루프에서 빠져 나옵니다. – pvg