简体   繁体   English

使用Python在关系数据库上循环

[英]Looping on a relational database with Python

I'm trying to figure out a python loop that would find the minimum cost to go from point A to point B within a given dataset. 我正在尝试找出一个python循环,该循环将找到在给定数据集中从A点到B点的最低成本。 For example, if someone wanted to fly from San Francisco to New York via the lowest cost with the below data. 例如,如果有人希望通过以下数据以最低的费用从旧金山飞往纽约。

sql.keys
# [u'id', u'departure', u'arrival', u'cost']

for i in sql:
  print i
#(0, u'San Francisco', u'New York', 600)
#(1, u'Denver', u'Chicago', 100)
#(2, u'New York', u'DC', 100)
#(3, u'Chicago', u'New York', 200)
#(4, u'San Francisco', u'Denver', 200)

With the above example, I'm hoping that the result will return the below: 对于上面的示例,我希望结果将返回以下内容:

(u'San Francisco', u'New York', 500)

Since someone can go between the two cities via SF -> Denver -> Chicago -> New York for 500 instead of flying direct for 600. 由于某人可以通过SF->丹佛->芝加哥->纽约在两个城市之间飞行,而不用直接飞行600来。

Thanks in advance! 提前致谢!

This is a standard graph problem for finding a shortest path in a graph. 这是用于在图中找到最短路径的标准图问题。

The most famous algorithm is Dijkstra 's. 最著名的算法是Dijkstra的算法。

If the data fits in memory, I would build an in memory graph and then apply the Dijkstra algorithm to it with starting node of 'San Francisco'. 如果数据适合内存,我将建立一个内存图,然后以“ San Francisco”的起始节点对其应用Dijkstra算法。 This would be faster than querying the database for each edge. 这比查询数据库的每个边缘要快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM