Python 优化这个解决方案,寻找公交网络中两个站点之间的最短路径

Python 优化这个解决方案,寻找公交网络中两个站点之间的最短路径,python,algorithm,Python,Algorithm,这个问题来自CodeEval open challenges,事实上,我尝试了许多方法来更快地解决这个问题,但结果只是“超出了时间”。问题的链接如下所示:。那么我的解决办法是: import sys import profile import array import collections def main(): with open(sys.argv[1], "r") as f: for line in f.readlines(): data

这个问题来自CodeEval open challenges,事实上,我尝试了许多方法来更快地解决这个问题,但结果只是“超出了时间”。问题的链接如下所示:。那么我的解决办法是:

import sys
import profile
import array
import collections

def main():
    with open(sys.argv[1], "r") as f:
        for line in f.readlines():
            data = line.strip().split('; ') 
            src, dst = map(int, data[0].strip('()').split(','))
            routes = [map(int, r.split('=')[1].strip('[]').split(',')) for r in data[1:]]
            #create a graph with the routes 
            #print "routes: %s" % routes
            start = 0
            g = {}
            node_ref = {}
            for r in routes:
                rlen = len(r)
                for i in range(rlen):
                    if i < rlen-1:
                        if start+i not in g:
                            g[start+i] = [(start+i+1, 7)]
                        else:
                            g[start+i].append((start+i+1, 7))
                        if start+i+1 not in g:
                            g[start+i+1] = [(start+i, 7)]
                        else:
                            g[start+i+1].append((start+i, 7))
                    if r[i] in node_ref:
                        for node in node_ref[r[i]]:
                            g[start+i].append((node, 12))
                            g[node].append((start+i, 12))
                    if r[i] not in node_ref:
                        node_ref[r[i]] = [start+i]
                    elif start+i not in node_ref[r[i]]:
                        node_ref[r[i]].append(start+i)
                start += rlen
            #print "create graph: %s" % g
            ans = 100000000
            #print node_ref[src]
            for s in node_ref[src]:
                visited = [False] * start
                costs = [100000000] * start
                costs[s] = 0
                get_cost(s, g, visited, costs)
                res = min([costs[node] for node in node_ref[dst]])
                if res < ans:ans = res
            if ans == 100000000:
                print "None"
            else:
                print ans
    sys.exit(0)

def get_cost(src, g, visited, costs):
    nq = collections.deque()
    nq.append(src)
    costs[src] = 0
    while nq:
        curnode = nq.popleft()
        visited[curnode] = True
        for (node, w) in g[curnode]:
            if not visited[node]:
                nq.append(node)
                if costs[node] > costs[curnode] + w:
                    costs[node] = costs[curnode] + w 

def test():
    g = {0: [(1, 7)], 1: [(0, 7), (2, 7)], 2: [(1, 7)], 3: [(4, 7), (11, 12)], 4: [(3, 7), (5, 7)], 5: [(4, 7), (6, 7)], 6: [(5, 7), (7, 7)], 7: [(6, 7)], 8: [(9, 7)], 9: [(8, 7), (10, 7)], 10: [(9, 7), (11, 7)], 11: [(10, 7), (3, 12)]}
    visited = [False] * 12
    costs = [100000000] * 12
    s = 3
    get_cost(s, g, visited, costs)
    print "src %d, costs: %s" % (s, costs) 
    #get_cost(3, g, visited, costs)
    #print "src 3, costs: %s" % 

if __name__ == '__main__':
    #profile.run("main();")
    main()
导入系统 导入资料 导入数组 导入集合 def main(): 打开(sys.argv[1],“r”)作为f: 对于f.readlines()中的行: 数据=line.strip().split(“;”) src,dst=map(int,数据[0].strip(“()”).split(“,”)) routes=[map(int,r.split('='))[1]。数据[1:]中r的strip('[]').split(',')) #创建包含路由的图形 #打印“路由:%s”%routes 开始=0 g={} 节点_ref={} 对于路线中的r: rlen=len(r) 对于范围内的i(rlen): 如果i成本[curnode]+w: 成本【节点】=成本【节点】+w def test(): g={0:[(1,7)],1:[(0,7),(2,7)],2:[(1,7)],3:[(4,7),(11,12)],4:[(3,7),(5,7)],5:[(4,7),(6,7)],6:[(5,7),(7)],8:[(9,7)],9:[(8,7),(10,7)],10:[(9,7),(11,7)],11:[(10,7),(10,7),(3,12)]] 已访问=[False]*12 成本=[100000000]*12 s=3 获取成本(s、g、访问、成本) 打印“src%d,成本:%s”%(s,成本) #获取成本(3,g,访问,成本) #打印“src 3,成本:%s”% 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': #profile.run(“main();”) main()
有人能提供一些建议来对此解决方案进行优化吗?

您提到的问题挑战似乎是,如果路径中包含特定的停止点,则需要最小长度的路径。这实际上比枚举一对停止点之间的所有简单路径要快得多。正如一条评论所建议的,使用Dijskra的多起点算法来获得站点之间最短路径的长度。参见,例如

简单的方法是复制要优化的相同代码,然后对其进行分析,以找到可以优化的代码,例如合并一些循环或使用常量而不是在计算中从不更改的部分,或以花费较少时间的不同方式进行计算,或使用更多空间赢得时间,使用一些数据结构为O(1)sYeah提供现成的数据访问,我已经尝试了你的建议。但这可能是一个耗费时间的问题,尤其是函数获取简单路径可能需要指数时间。也许应该有更好的解决方案来解决这个问题,而不是这个。如果你从一个代码开始,你有相同的时间,如果你修改了该代码中的某些内容并获得了更多的时间,那么该更改是错误的,请返回并尝试不同的方法。。否则你要求的不是优化——使用Dijkstra算法。是的,你是对的。我尝试了Dijskra的算法来解决这个问题,但时间还是超过了。我已经更改了问题中的代码。也许这次我真的需要做优化。