Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - find longest path

Tags:

python

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. 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!

like image 698
aRandomStudent Avatar asked Jan 14 '17 01:01

aRandomStudent


2 Answers

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:

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")
like image 69
DYZ Avatar answered Sep 19 '22 01:09

DYZ


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
like image 36
Batman Avatar answered Sep 21 '22 01:09

Batman