微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法在执行过程中更改 networkx 中边的权重

如何解决有没有办法在执行过程中更改 networkx 中边的权重

我正在 django (python) 中制作一个旅行应用程序。

我有关于旅行的信息,我需要应用 Dijkstra 的算法来评估是否可以使用接送服务。我需要下面的行程在算法中的前面一个之后。

我想将 networkx 与 Dijkstra 算法一起使用,但我不知道我是否可以或是否必须避免使用 networkx 来解决我的问题。

我创建了一个图表(使用熊猫读取 csv 文件)。每个节点都是一个机场,每次旅行都是一条边

DG=nx.DiGraph()
for row in spain_flights.iterrows():
    DG.add_edge(row[1]["origin"],row[1]["destination"],duration=row[1]["duration"],price=row[1]["price"])

然后我可以找到最佳路线(考虑价格(或持续时间)):

list(nx.dijkstra_path(DG,source="PNA",target="VLL",weight="price"))

但是如果我想考虑一个特定的时间,我不知道如何解决。因为后面的行程不可能在实际行程之前

解决方法

我猜你问的问题解决了:

import networkx as nx
from networkx.algorithms.shortest_paths.weighted import dijkstra_path

airports = [
    (1,2,{"price": 100}),(1,3,{"price": 200}),(3,{"price": 300}),4,(4,5,{"price": 50}),{"price": 500}),]


user_path = [(1,2),(2,3),5)] # a route given to you by the user

G = nx.Graph()
G.add_edges_from(airports)


# calculate how much the user's journey costs 
user_price = 0
for (src,dst) in user_path:
    user_price += G[src][dst]["price"]

dijkstra_path = dijkstra_path(G,source=1,target=5,weight="price")
dijkstra_price = 0

# calculate how much the dijkstra's journey for the same route costs
for node in range(0,len(dijkstra_path)):
    if node + 1 == len(dijkstra_path):
        break
    dijkstra_price += G[dijkstra_path[node]][dijkstra_path[node + 1]]["price"]

if user_price > dijkstra_price:
    print("User chose a bad route")
else:
    print("User chose a route with optimal price.")

path: [(1,5)]

outputs: 
User chose a bad route
path:[(1,4),5)]

outputs:
User chose a route with optimal price.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。