python – 列车路线的最佳数据结构?

python – 列车路线的最佳数据结构?,第1张

概述所以我的任务基本上是读取一个文件(记事本文件),该文件有一堆列车停靠点以及从一站到另一站的时间.例如,它看起来像: Stop A 15Stop B 12Stop C 9 现在我需要返回并访问这些站点及其时间.我正在考虑阅读文件并将其存储为字典.我的问题是,字典是否最适合这个?或者是否有一些其他python工具会更有用?任何想法将不胜感激! 我会反对这种说法 – 并说直言 所以我的任务基本上是读取一个文件(记事本文件),该文件有一堆列车停靠点以及从一站到另一站的时间.例如,它看起来像:

Stop A     15Stop B     12Stop C     9

现在我需要返回并访问这些站点及其时间.我正在考虑阅读文件并将其存储为字典.我的问题是,字典是否最适合这个?或者是否有一些其他python工具会更有用?任何想法将不胜感激!

解决方法 我会反对这种说法 – 并说直言不讳是不是最好的.

假设您有100个停靠点和多个非字母和非数字路线.想想巴黎地铁:

现在尝试使用直接的Python dict来计算fdr和La Fourche之间的时间?这涉及两个或更多不同的路线和多个选项.

tree或某种形式的graph是更好的结构.对于1对1的映射,dict非常棒;树对于彼此相关的节点的丰富描述更好.然后,您将使用类似Dijkstra’s Algorithm的东西进行导航.

由于nested dict of dicts or dict of lists是一个图表,很容易想出一个递归的例子:

def find_all_paths(graph,start,end,path=[]):        path = path + [start]        if start == end:            return [path]        if start not in graph:            return []        paths = []        for node in graph[start]:            if node not in path:                newpaths = find_all_paths(graph,node,path)                for newpath in newpaths:                    paths.append(newpath)        return paths       def min_path(graph,end):    paths=find_all_paths(graph,end)    mt=10**99    mpath=[]    print '\tAll paths:',paths    for path in paths:        t=sum(graph[i][j] for i,j in zip(path,path[1::]))        print '\t\tevaluating:',path,t        if t<mt:             mt=t            mpath=path    e1=' '.join('{}->{}:{}'.format(i,j,graph[i][j]) for i,j in zip(mpath,mpath[1::]))    e2=str(sum(graph[i][j] for i,mpath[1::])))    print 'Best path: '+e1+'   Total: '+e2+'\n'  if __name__ == "__main__":    graph = {'A': {'B':5,'C':4},'B': {'C':3,'D':10},'C': {'D':12},'D': {'C':5,'E':9},'E': {'F':8},'F': {'C':7}}    min_path(graph,'A','E')    min_path(graph,'D')    min_path(graph,'F')

打印:

All paths: [['A','C','D','E'],['A','B','E']]        evaluating: ['A','E'] 25        evaluating: ['A','E'] 29        evaluating: ['A','E'] 24Best path: A->B:5 B->D:10 D->E:9   Total: 24    All paths: [['A','D'],'D']]        evaluating: ['A','D'] 16        evaluating: ['A','D'] 20        evaluating: ['A','D'] 15Best path: A->B:5 B->D:10   Total: 15    All paths: [['A','E','F'],'F']]        evaluating: ['A','F'] 33        evaluating: ['A','F'] 37        evaluating: ['A','F'] 32Best path: A->B:5 B->D:10 D->E:9 E->F:8   Total: 32
总结

以上是内存溢出为你收集整理的python – 列车路线的最佳数据结构?全部内容,希望文章能够帮你解决python – 列车路线的最佳数据结构?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1194892.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存