亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于源-目的字典計算源路徑

基于源-目的字典計算源路徑

鳳凰求蠱 2021-10-12 15:07:25
我有一個輸入字典 -dict_input目標為keys,源為values。一個目的地可以有一個或多個來源。dict_input = {'C411':['C052'],'C052':['C001','C002'], 'C001':['9001'], 'C002':['9002']}在上面dict_input,終端目的地是,C411而初始來源是9001和9002。我正在嘗試為終端目的地提出源路徑C411。預期輸出形式為list-[['C411', 'C052', 'C001', '9001'], ['C411', 'C052','C002', '9002']]我有這個代碼:def get_source(node, dict_input, source=[]):    if node in dict_input:        source.append(node)        for i in dict_input[node]:            if i != node:                get_source(i, dict_input, source)            else:                source.append(node)    else:        source.append(node)        return source    return sourcedict_input = {'C052':['C001','C002'], 'C411':['C052'], 'C001':['9001'], 'C002':['9002']} print(get_source('C411', dict_input, []))輸出是合并成一個列表的兩個源路徑 -['C411', 'C052', 'C001', '9001', 'C002', '9002']如何修改我的代碼以獲取每個源路徑的單獨列表?
查看完整描述

1 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

pop完成訪問節點后不要忘記從當前路徑

如果遇到“葉子”(不是鍵的節點 ID),則在輸出列表中存儲當前路徑的副本

警惕損壞的數據,例如循環鏈接 - 將有助于保留set訪問過的節點

上面的示例實現:


def get_source(root, dict_input):


    # output list

    path_list = []


    # current path

    cur_path = []


    # visited set

    visited = set()


    # internal recursive helper function

    def helper(node):

        cur_path.append(node)


        # normal node

        if node in dict_input:

            if not node in visited:

                visited.add(node)

                for child in dict_input[node]:

                    helper(child)


            # else: cycle detected, raise an exception?


        # leaf node

        else:

            # important: must be a copy of the current path

            path_list.append(list(cur_path))


        cur_path.pop()


    # call this helper function on the root node

    helper(root)


    return path_list

測試:


>>> dict_input = {'C411':['C052'],'C052':['C001','C002'], 'C001':['9001'], 'C002':['9002']}


>>> get_source('C411', dict_input)

[['C411', 'C052', 'C001', '9001'], ['C411', 'C052', 'C002', '9002']]


查看完整回答
反對 回復 2021-10-12
  • 1 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號