簡體   English   中英

在Python中的有向圖中查找路徑

[英]Finding a path in a directed graph in Python

我是Python初學者。 我希望從頭開始學習,因此請保持與我的水平一致的建議,避免使用高級構造或圖形庫。

我有一個有向圖,如下所示:

test= {
'a':    [['b'],     ['Starfleet Commander', 'Ninja Hamsters', 'Seahorse Adventures']], 
'b':    [['c'],     ['Call of Arms', 'Dwarves and Swords', 'The Movie: The Game']], 
'c':    [['e','d'],     ['Seven Schemers', 'Pirates in Java Island', 'Dwarves and Swords']], 
'd':    [[],    ['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom Man']],
'e':    [[],            ['Seven Schemers', 'Pirates in Java Island', 'Dwarves and Swords']], 
}

現在,我創建一個遞歸方法以返回源和目標之間的路徑:

def path_to_friend(network, source, destination):
if source == destination:
    return [destination]
else:
    for new_source in network[source][0]:

            #print 'source> '+ source + '; new source> ' + new_source
            try:
                return [source] + path_to_friend(network, new_source, destination)
            except TypeError, e:
                print source, new_source, destination, e
                pass

並進行函數調用:

print path_to_friend(test, 'a', 'd')

對於遞歸遵循沒有值的節點/鍵“ e”的情況,這將失敗。 返回的錯誤是:

只能串聯列表(不是“ NoneType”)到列表

如果“ c”的圖形條目更改為:

'c':    [['d','e'],     ['Seven Schemers', 'Pirates in Java Island', 'Dwarves and Swords']]

因此在“ e”之前到達“ d”,則不會引發錯誤。

問題是此信息不足以讓我理解我的代碼為何會創建此錯誤。 我聽不懂這門語言的基本知識。

請指教。

您需要使用遞歸方法嗎? 如果沒有,您可以使用BFS搜索。 看看這種解決問題的方法

您的代碼在這里有很多問題。 首先,如果Node(A)和Node(B)之間不存在路徑,則該函數返回None

並且由於在下一次恢復中,您嘗試添加[source] + path_to_friend(network, new_source, destination) ,這基本上等效於[source] + None ,它將簡單地失敗並引發您剛剛遇到的錯誤。 為了解決這個問題,我們只需要測試path_to_friend的結果,然后再將其添加到結果中即可

def path_to_friend(network, source, destination):
    if source == destination:
        return [destination]
    else:
        for new_source in network[source][0]:

                #print 'source> '+ source + '; new source> ' + new_source
                sub_path = path_to_friend(network, new_source, destination)
                if sub_path is not None:
                    return [source] + sub_path

您可能會遇到的第二個問題是網絡中存在循環。 在這種情況下,您可能會陷入無限循環:

節點A訪問節點B,節點B又訪問節點A ....

為了解決這個問題,我們將使用一個跟蹤訪問的節點並將其傳遞給函數的集合

def path_to_friend(network, source, destination, visited=None):
    if source == destination:
        return [destination]
    else:
        visited = visited or set()
        for new_source in network[source][0]:
                if new_source not in visited: # check if the next node was already visited
                    visited.add(new_source) # add the next node to the list of visited nodes
                    #print 'source> '+ source + '; new source> ' + new_source
                    sub_path = path_to_friend(network, new_source, destination, visited)
                    if sub_path is not None:
                        return [source] + sub_path

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM