簡體   English   中英

如何在python中查找從給定節點到所有葉節點的路徑

[英]How to find path from a given node to all leaf nodes in python

我有一本字典,其中有與每個節點關聯的父子節點列表(代碼中的字典引用)。 我將輸入一個鍵(對於下面的代碼段B是鍵)。 我必須考慮父節點。 對於B我想要的路徑為[B,C,C1,X],[B,C,C2],[B,D,D1],[B,D,D2]

我獲得的以下代碼的輸出是:

C ['C1', 'C2']

C1 ['X']

我也收到以下錯誤:

如果d [i] ['parent'] == [key],則在path_find中的文件“”的第7行:

KeyError:“ X”

def path_find(graph,key):

    x = d[key]['child'] 
    for i in x:
        if d[i]['parent'] == [key]:
            print(i,d[i]['child'])
            path_find(d,i)


d = {'B':{
 'parent' : ['A'],
  'child': ['C','D']},
'C':{
'parent' : ['B'],
'child' : ['C1','C2']},
        'D':{
 'parent' : ['B'],
  'child': ['D1','D2']},
    'C1':{
            'parent' : ['C'],
            'child': ['X']}}

key = 'B'
path_find(d,key)

預期的輸出是: [B, C, C1, X], [B, C, C2], [B, D, D1], [B, D, D2]

實際輸出為:

C ['C1', 'C2']

C1 ['X']

您的代碼中幾乎沒有錯誤:

1)您沒有在d = { ... }添加有關X節點的信息,這就是為什么出現KeyError的原因。 我想這是一個沒有孩子的節點。

2)您沒有保存到當前節點的路徑,因此您的輸出無效。

更正的代碼(帶有我的評論):

def path_find(graph, key, current_path, paths_list):  # graph, current node key, path to current node, all paths list
    if key not in d: # not in graph - no children
        paths_list.append(current_path)
        return
    children = d[key]['child'] 
    for child in children:  # check all children
        path_find(graph, child, current_path[:] + [child], paths_list)
    if not children:  # no children - finish search
        paths_list.append(current_path)


d = {'B':{
 'parent' : ['A'],
  'child': ['C','D']},
'C':{
'parent' : ['B'],
'child' : ['C1','C2']},
        'D':{
 'parent' : ['B'],
  'child': ['D1','D2']},
    'C1':{
            'parent' : ['C'],
            'child': ['X']}}

key = 'B'
paths_list = []
path_find(d, key, [key], paths_list)
print(paths_list)

輸出:

[['B','C','C1','X'],['B','C','C2'],['B','D','D1'],['B ','D','D2']]

暫無
暫無

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

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