IndexError:列表索引超出范围图表直径

时间:2014-11-22 16:43:28

标签: python graph indexing range

这是我的代码:

class Graph(object):

def __init__(self, graph_dict={}):
    self.__graph_dict = graph_dict

def vertices(self):
    return list(self.__graph_dict.keys())


def find_all_paths(self, start_vertex, end_vertex, path=[]):
    graph = self.__graph_dict
    path = path + [start_vertex]
    if start_vertex == end_vertex:
        return [path]
    if start_vertex not in graph:
        return []
    paths = []
    for vertex in graph[start_vertex]:
        if vertex not in path:
            extended_paths = self.find_all_paths(vertex, 
                                             end_vertex, 
                                             path)
            for p in extended_paths:
                paths.append(p)


    return paths

def diameter(self):


    v = self.vertices() 
    pairs = [ (v[i],v[j]) for i in range(len(v)) for j in range(i+1, len(v)-1)]
    smallest_paths = []
    for (s,e) in pairs:
        paths = self.find_all_paths(s,e)
        smallest = sorted(paths, key=len)[0]
        smallest_paths.append(smallest)

    smallest_paths.sort(key=len)


    diameter = len(smallest_paths[-1])
    return diameter    

当我执行命令时:

if __name__ == "__main__":

from collections import defaultdict
g = defaultdict(list)
with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
    for line in f:
        key, val = line.split()
        g[key].append(val)
for k, v in g.items():
    print(k, v)

    graph = Graph(g)

print("Vertices of graph:")
print(graph.vertices())
print(graph.find_all_paths("0", "3"))

print(graph.diameter())

我收到此错误: 文件"",第70行,in     打印(graph.diameter())

文件"",第40行,直径     smallest = sorted(paths,key = len)[0]

IndexError:列表索引超出范围

图表非常大。它有3633个边缘。 我收到此错误的原因是什么? 我可以用另一个函数来计算这个图的直径吗?

0 个答案:

没有答案