开发者

Pygraph - path between two nodes with specific weight

I want to find a path in a graph that has connects two nodes and does not use the same node twice. The sum of the weights of the edges must be within a certain range.

I need to implement this in pygraph. I'm not sure if 开发者_开发百科there is already an algorithm that I can use for this purpose or not. What's the best way to achieve this?


EDIT: I misunderstood the question initially. I've corrected my answer. This functionality isn't built into the pygraphlib library, but you can easily implement it. Consider something like this, which basically gets the shortest path, decides if it's in a predefined range, then removes the edge with the smallest weight, and computes the new shortest path, and repeats.

from pygraphlib import pygraph, algo

edges = [(1,2),(2,3),(3,4),(4,6),(6,7),(3,5),(4,5),(7,1),(2,5),(5,7)]
graph = pygraph.from_list(edges)

pathList = []
shortestPath = algo.shortest_path(graph, startNode, endNode)
cost = shortestPath[len(shortestPath)-1][1]

while cost <= maxCost:
    if cost >= minCost:
        pathList.append(shortestPath)

    minEdgeWt = float('inf')
    for i in range(len(shortestPath)-1):
        if shortestPath[i+1][1] - shortestPath[i][1] < minEdgeWt:
            minEdgeWt = shortestPath[i+1][1] - shortestPath[i][1]
            edgeNodes = (shortestPath[i][0], shortestPath[i+1][0])

    #Not sure of the syntax here, edgeNodes is a tuple, and hide_edge requires an edge.
    graph.hide_edge(edgeNodes)
    shortestPath = alog.shortest_path(graph, startNode, endNode)
    cost = shortestPath[len(shortestPath)-1][1]

return pathList

Note that I couldn't find a copy of pygraphlib, seeing as it is no longer under development, so I couldn't test the above code. It should work, mod the syntax uncertainty. Also, if possible, I would recommend using networkx[link] for any kind of graph manipulation in python, as it is more complete, under active development, and more completely documented then pygraphlib. Just a suggestion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜