I’m learning Python and for practicing purposes I’m writing a script that reads a file (containing a graph in Trivial Graph Format) and runs a couple of graph algorithms on the graph.
I thought about storing the graph in a list of n dictionaries, where n is the number of vertexes and all the edges of a vertex would be stored in a dictionary.
I tried this
edges = [{} for i in xrange(num_vertexes)]
for line in file:
args = line.split(' ')
vertex1 = int(args[0])
vertex2 = int(args[1])
label = int(args[2])
edges[vertex1][vertex2] = label
but I’m getting this error for the last line:
IndexError: list index out of range
It looks like
vertex1is probably greater thannum_vertexes. Given that python indexes from 0 and the example on the wiki of the format goes from 1, the last line’s vertex number is probably 1 higher than the length of the index (I’d need to see the file to know for sure, of course). So in the python caselst[0]is the first element, andlst[n-1]is the last element where for the vertexes1is the first element andnis the last element.So the fix here is to use
vertex1 = int(args[0])-1