ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sat, 02 May 2020 17:37:46 +0200Graph indexed from zerohttps://ask.sagemath.org/question/51211/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?Sat, 02 May 2020 17:01:38 +0200https://ask.sagemath.org/question/51211/graph-indexed-from-zero/Answer by SYLA for <p>How to change vertices of a graph to that are indexed from 0?</p>
<p>In Mathematica: ChangeVertices.</p>
<p>We can change it to the adjacency matrix A and from A to the graph. A faster solution?</p>
<p>Ho to get a permutation of vertices?</p>
https://ask.sagemath.org/question/51211/graph-indexed-from-zero/?answer=51214#post-id-51214Maybe faster than that:
def ChangeVertices(g,di):
G=Graph()
for v in di.values():
G.add_vertex(v)
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())}))Sat, 02 May 2020 17:28:01 +0200https://ask.sagemath.org/question/51211/graph-indexed-from-zero/?answer=51214#post-id-51214Answer by Sébastien for <p>How to change vertices of a graph to that are indexed from 0?</p>
<p>In Mathematica: ChangeVertices.</p>
<p>We can change it to the adjacency matrix A and from A to the graph. A faster solution?</p>
<p>Ho to get a permutation of vertices?</p>
https://ask.sagemath.org/question/51211/graph-indexed-from-zero/?answer=51215#post-id-51215There 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](http://doc.sagemath.org/html/en/reference/graphs/sage/graphs/generic_graph.html#sage.graphs.generic_graph.GenericGraph.relabel) method which has many options.Sat, 02 May 2020 17:37:46 +0200https://ask.sagemath.org/question/51211/graph-indexed-from-zero/?answer=51215#post-id-51215