# Graph indexed from zero

How to change vertices of a graph to that are indexed from 0?

In Mathematica: ChangeVertices.

We can change it to the adjacency matrix A and from A to the graph. A faster solution?

Ho to get a permutation of vertices?

edit retag close merge delete

Sort by » oldest newest most voted

There is a method called relabel for that:

sage: g = Graph([('a','b'), ('b','c')])
sage: g.vertices()
['a', 'b', 'c']
sage: g.relabel()
sage: g.vertices()
[0, 1, 2]
sage: g.edges()
[(0, 1, None), (1, 2, None)]


To make sure of what it does, you may provide the permutation yourself as a dictionary:

sage: g = Graph([('a','b'), ('b','c')])
sage: g.relabel({'a':1,'b':2,'c':0})
sage: g.edges()
[(0, 2, None), (1, 2, None)]


See documentation of relabel method which has many options.

more

Maybe faster than that:

def ChangeVertices(g,di):
G=Graph()
for v in di.values():
for e in g.edge_iterator():
G.add_edge(di[e[0]] if e[0] in di else e[0],di[e[1]] if e[1] in di else e[1])
return(G)

def GraphFromZero(g):
return(ChangeVertices(g,{v:i for i,v in enumerate(g.vertices())}))

more