2016-03-18 51 views
1

我有这两个功能找到一个图中的循环(这是一本字典)更新指针:蟒蛇 - 如何在整个功能

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。为什么不更新?

回答

0

您正在为found_cycle分配一个新列表,这意味着调用函数中不会发生任何更改。因此,假设你的意思是更新原有的列表中,您可以:

found_cycle[0] = True 
found_cycle[1] = v 

或者更简单地用一个切片赋值:

found_cycle[:] = [True, v] 

或者刚刚从dfs_visit()返回值。

0

这两个found_cycle对每个功能都是本地的,不能共享。你应该返回它的值,并重新分配给它:

def cycle_exists(G): 
    ... 
     found_cycle = dfs_visit(G, u, color, found_cycle) 

def dfs_visit(G, u, color, found_cycle): 
    ... 
     return found_cycle 
     ... 
      return found_cycle 
+1

'found_cycle'是这样,可以通过更新 - 名单并非一成不变,然而'return'ing的值是一个好得多的方法。 – AChampion