[英]Python - find longest path
The function will take in a dictionary as input, and I want to find the length of a longest path in a dictionary. 该函数将字典作为输入,我想在字典中找到最长路径的长度。 Basically, if in a dictionary, key2 matches value1, and key3 matches value2, and so forth, this counts as a path. 基本上,如果在字典中,key2与value1匹配,key3与value2匹配,依此类推,则计为路径。 For example: 例如:
{'a':'b', 'b':'c', 'c':'d'}
In the case above, the length should be three. 在上面的例子中,长度应该是三。 How would I achieve this? 我怎么做到这一点? Or more specifically how would I compare keys to values? 或者更具体地说,我如何比较键值? (it could be anything, strings, numbers, etc., not only numbers) (它可以是任何东西,字符串,数字等,而不仅仅是数字)
Many thanks in advance! 提前谢谢了!
I would treat the dictionary as a list of edges in a directed acyclic graph (DAG) and use the networkx
module to find the longest path in the graph: 我会将字典视为有向非循环图(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")
If you're insisting on not importing anything you could do something like: 如果你坚持不进口任何东西,你可以这样做:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.