Python - 找到最长的路径

时间:2017-01-14 01:17:37

标签: python

该函数将字典作为输入,我想在字典中找到最长路径的长度。基本上,如果在字典中,key2与value1匹配,key3与value2匹配,依此类推,则计为路径。例如:

{'a':'b', 'b':'c', 'c':'d'}

在上述情况下,长度应为3。我怎么做到这一点?或者更具体地说,我如何比较键值? (它可以是任何东西,字符串,数字等,而不仅仅是数字)

非常感谢提前!

2 个答案:

答案 0 :(得分:6)

我会将字典视为有向非循环图(DAG)中的边列表,并使用networkx模块查找图中最长的路径:

import networkx as nx

data = {'a':'b', 'b':'c', 'c':'d'}

G = nx.DiGraph()
G.add_edges_from(data.items())
try:
  path = nx.dag_longest_path(G)
  print(path)
  # ['a', 'b', 'c', 'd']

  print(len(path) - 1)
  # 3
except nx.exception.NetworkXUnfeasible: # There's a loop!
  print("The graph has a cycle")

答案 1 :(得分:1)

如果您坚持不导入任何内容,可以执行以下操作:

def find_longest_path(data):
    longest = 0
    for key in data.iterkeys():
        seen = set()
        length = -1
        while key:
            if key in seen:
                length = -1
                raise RuntimeError('Graph has loop')
            seen.add(key)
            key = data.get(key, False)
            length += 1
        if length > longest:
            longest = length

    return longest