![](/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.