![](/img/trans.png)
[英]Find all possible paths in a python graph data structure without using recursive function
[英]How to get multiple paths returned in a Python recursive graph function?
1) 假設 A1、B1 和 C1 是該圖中的節點。 C1 在 B1 的上游,B1 在 A1 的上游。 見這張圖片: https://imgur.com/fHxuCpH
如果我調用get_path_to_most_upstream(A1,[])
那么我得到[[A1, B1, C1]]
。
2) 但是,當一個節點的上游有多個父節點時,這不起作用。 見這張圖片: https://imgur.com/YQ5Q1zx
當我調用get_path_to_most_upstream(A1,[])
時,我得到一個空列表[]
但我想得到[[A1, B1, C1],[A1,B1,C2],[A1,B2,C3],[A1,B2,C4]]
。 我該如何調整這個 function 以返回它?
def get_path_to_most_upstream(start_key, path):
current_top = start_key
path = path + [current_top] #add top node to path
parents = get_nodes_upstream_one_hop(current_top) #returns list of nodes directly above
#parents = [B1] in first case
#parents = [B1, B2] in second
if not parents: #base case
return [path]
paths = []
for parent in parents:
if parent not in path:
extended_paths = get_path_to_most_upstream(parent, path)
for p in extended_paths:
paths.append(p)
return paths
您的代碼適用於小型 mod。
模組
在 function get_path_to_most_upstream 中給出路徑默認值 None
get_path_to_most_upstream(start_key, path = None):
如果路徑為無,則將路徑設置為列表
如果路徑為無:路徑 = []
重構代碼
def get_nodes_upstream_one_hop(node):
return [neighbor for neighbor in graph[node]]
def get_path_to_most_upstream(start_key, path = None):
if path is None:
path = []
current_top = start_key
path = path + [current_top] #add top node to path
parents = get_nodes_upstream_one_hop(current_top) #returns list of nodes directly above
#parents = [B1] in first case
#parents = [B1, B2] in second
if not parents: #base case
return [path]
paths = []
for parent in parents:
if parent not in path:
extended_paths = get_path_to_most_upstream(parent, path)
for p in extended_paths:
paths.append(p)
return paths
圖形代碼
from collections import defaultdict
# function for adding edge to graph
graph = defaultdict(list)
def addEdge(graph,u,v):
graph[u].append(v)
# definition of function
def generate_edges(graph):
edges = []
# for each node in graph
for node in graph:
# for each neighbour node of a single node
for neighbour in graph[node]:
# if edge exists then append
edges.append((node, neighbour))
return edges
測試
測試 1
graph = defaultdict(list)
addEdge(graph, 'A1', 'B1')
addEdge(graph, 'B1', 'C1')
print(get_path_to_most_upstream('A1')) # [['A1', 'B1', 'C1']]
測試 2
graph = defaultdict(list)
addEdge(graph, 'A1', 'B1')
addEdge(graph, 'A1', 'B2')
addEdge(graph, 'B1', 'C1')
addEdge(graph, 'B1', 'C2')
addEdge(graph, 'B2', 'C3')
addEdge(graph, 'B2', 'C4')
print(get_path_to_most_upstream('A1'))
# [['A1', 'B1', 'C1'],
# ['A1', 'B1', 'C2'],
# ['A1', 'B2', 'C3'],
# ['A1', 'B2', 'C4']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.