在Python中,如何获得对应于图中特定长度的所有可能路径的边值列表?

2024-04-25 16:47:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下图表(相应的边值写在括号中):

L0 -> L1 ('01')
L1 -> L2 ('12')
L1 -> L4 ('14')
L4 -> L5 ('45')
L2 -> L3 ('23')
L3 -> L1 ('31')

现在我需要从L0开始的所有可能路径的边值的列表。因此,如果length = 3(不包括起始节点),我应该得到两个列表:

['01', '12', '23'] and ['01', '14', '45'].

允许循环遍历。我试着用两级字典来表示这个图。你知道吗

graph = {'L0': {'L1': '01'}, 'L1': {'L2': '12', 'L4': '14'}, 'L2': {'L3': '23'}, 'L3': {'L1': '31'}, 'L4': {'L5': '45'}}

def find_path(graph, start, depth):
    k = 0
    while k < depth:
        a = graph[start]
        for node in graph[start]:
            start = node
        path.append(a[node])
        k+=1 
    return path 
print find_path(graph, 'L0', 4)

显然,它给出了一个可能的路径输出。但我想要所有可能的。你知道吗


Tags: path路径nodel1列表findstartgraph
2条回答

我会让它递归地继续前进,直到达到极限或者无法继续前进。你知道吗

# graph: Graph we are operating on
# node: Node we are starting from
# hops: Number of hops we can still do (edges we can take)
def findPaths(graph, node, hops):
    # if no further hops should be done, we were successful and
    # can end the recursion
    if hops == 0:
        yield []
        return

    # if the node is not in the graph, we cannot go further, so
    # the current path is invalid
    if node not in graph:
        return

    # for every node we can reach from the current
    for n in graph[node]:
        # find all paths we can take from here
        for path in findPaths(graph, n, hops - 1):
            # and concat the edge names
            yield [graph[node][n]] + path

在图形上使用(在给定的表示形式中),可以得到:

>>> list(findPaths(graph, 'L0', 3))
[['01', '14', '45'], ['01', '12', '23']]
>>> list(findPaths(graph, 'L0', 4))
[['01', '12', '23', '31']]
>>> list(findPaths(graph, 'L0', 2))
[['01', '14'], ['01', '12']]

我将它表示为一个简单的edge:edge字典:

links = {
    0: [1],
    1: [2, 4],
    2: [3],
    4: [5],
    3: [1]
}

然后你可以迭代它:

def get_all_paths(links, length, start=0):
    paths = [[start]]
    for i in range(length):
        newpaths = []
        for path in paths:
            try:
                for next_node in links[path[-1]]:
                    newpaths.append(path + [next_node])
            except KeyError:
                pass
        paths = newpaths

    return paths

get_all_paths(links, 3)
#>>> [[0, 1, 2, 3], [0, 1, 4, 5]]

每个[0, 1, 2, 3][(0,1), (1,2), (2,3)]的转换可以在单独的步骤中完成。你知道吗


它也适用于图形:

links = {'L0': {'L1': '01'}, 'L1': {'L2': '12', 'L4': '14'}, 'L2': {'L3': '23'}, 'L3': {'L1': '31'}, 'L4': {'L5': '45'}}

def get_all_paths(links, length, start=0):
    paths = [[start]]
    for i in range(length):
        newpaths = []
        for path in paths:
            try:
                for next_node in links[path[-1]]:
                    newpaths.append(path + [next_node])
            except KeyError:
                pass
        paths = newpaths

    return paths

get_all_paths(links, 3, start='L0')
#>>> [['L0', 'L1', 'L4', 'L5'], ['L0', 'L1', 'L2', 'L3']]

然后可以将每个路径转换为['01', '14', '45']形式。你知道吗


既然您似乎想知道如何进行最后的转换,这里有一个方法:

paths = [['L0', 'L1', 'L4', 'L5'], ['L0', 'L1', 'L2', 'L3']]

def join_paths(paths, links):
    for path in paths:
        yield [links[a][b] for a, b in zip(path, path[1:])]

list(join_paths(paths, links))
#>>> [['01', '14', '45'], ['01', '12', '23']]

zip(path, path[1:])[1, 2, 3, 4]变成[(1, 2), (2, 3), (3, 4)]。你知道吗

for a, b in将获取每一对,并将ab设置为其中的项。你知道吗

然后links[a][b]将从字典中查找路径名。你知道吗

yield一次返回一个项目,因此必须对join_paths的输出调用list才能将其放入列表中。你知道吗

相关问题 更多 >