Ask Your Question

Graph indexed from zero

asked 2020-05-02 10:01:38 -0500

SYLA gravatar image

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 flag offensive close merge delete

2 answers

Sort by » oldest newest most voted

answered 2020-05-02 10:37:46 -0500

Sébastien gravatar image

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.

edit flag offensive delete link more

answered 2020-05-02 10:28:01 -0500

SYLA gravatar image

Maybe faster than that:

def ChangeVertices(g,di):  
    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])

def GraphFromZero(g):
    return(ChangeVertices(g,{v:i for i,v in enumerate(g.vertices())}))
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-05-02 10:01:38 -0500

Seen: 41 times

Last updated: May 02