我有这两个功能找到一个图中的循环(这是一本字典)更新指针:蟒蛇 - 如何在整个功能
def cycle_exists(G):
color = { u : "white" for u in G}
found_cycle = [False]
for u in G:
if color[u] == "white":
dfs_visit(G, u, color, found_cycle)
if found_cycle[0]:
break
if not found_cycle[0]:
return None
return found_cycle[1]
def dfs_visit(G, u, color, found_cycle):
if found_cycle[0]:
return
color[u] = "gray"
for v in G[u]:
if color[v] == "gray":
found_cycle = [True, v]
return
if color [v] == "white":
dfs_visit(G, v, color, found_cycle)
color[u] = "black"
当一个周期dfs_visit
被发现,found_cycle
被分配[True, v]
,但是当Python返回到cycle_exists
函数时,found_cycle
仍然是False
。为什么不更新?
'found_cycle'是这样,可以通过更新 - 名单并非一成不变,然而'return'ing的值是一个好得多的方法。 – AChampion