0

So my problem is to find the longest path from a node to another node (or the same node) in a graph implemented with Networkx library.

I don't want to add the edges' weights but multiply them and take the biggest result. Obviously, passing only once by each node or not at all.

For example if I want to go from node 1 to node 4, the best result would be : 2 x 14 x 34 x 58

Graph example

Thank you for your help !

pokatore
  • 51
  • 1
  • 7
  • are you guaranteed all weights >1? – Joel Nov 17 '17 at 03:27
  • This looks a bit like it could be a homework question... So just a hint, rather than a full answer - what operation satisfies f(ab) = f(a) + f(b)? Once you've accounted for that, is it possible to use a networkx algorithm for finding the path with least sum? – Joel Nov 17 '17 at 06:27
  • Thank you Joel ! It's the log function. And it's something that I am trying to implement but I don't know much about programming. – pokatore Nov 17 '17 at 09:59
  • So what have you tried? – Joel Nov 17 '17 at 16:00
  • Ouch - I just realized you're after longest path, not shortest path. That's NP hard: https://en.wikipedia.org/wiki/Longest_path_problem – Joel Nov 19 '17 at 07:38

1 Answers1

0

This may work:

import networkx as nx

G = nx.Graph()

# create the graph
G.add_edge(1, 2, weight=2 )
G.add_edge(1, 4, weight=5 )
G.add_edge(2, 3, weight=14 )
G.add_edge(2, 4, weight=5 )
G.add_edge(2, 5, weight=4 )
G.add_edge(3, 5, weight=34 )
G.add_edge(4, 5, weight=58 )

start = 1 # start node
end = 4   # end node

all_paths = [path for path in nx.all_simple_paths(G, start, end)]

# initialize result
largest_path = None
largest_path_weight = None

# iterate through all paths to find the largest
for p in all_paths:                                       # keep track of each path
    for _ in range(len(p)):                               # for each node in this path
        pairs = zip(p, p[1:])                             # get sequence of nodes
        product = 1                                       # reset product for this paths calculation
        for pair in pairs:                                # for each pair of nodes in this path
            an_edge = G.get_edge_data(pair[0], pair[1])   # get this edge's data
            product *= an_edge['weight']                  # multiply all weights
    if product > largest_path_weight:                     # check if this path's product is greater
        largest_path = p                                  # if True, set largest to this path
        largest_path_weight = product                     # save the weight of this path

# display result
print 'largest path:', largest_path 
print 'weight:', largest_path_weight

for this example:

largest path: [1, 2, 3, 5, 4]
weight: 55216