Ask Your Question
0

Does Sage have a built-in function to output an adjacency list?

asked 2024-07-23 15:30:22 +0100

licheng gravatar image

We know that SageMath supports adjacency list input, but I haven't seen an output function.

Graph({0: [1, 5, 7, 8, 11],
 1: [0, 2, 5, 6, 8],
 2: [1, 3, 6, 8, 9],
 3: [2, 4, 6, 9, 10],
 4: [3, 5, 6, 10, 11],
 5: [0, 1, 4, 6, 11],
 6: [1, 2, 3, 4, 5],
 7: [0, 8, 9, 10, 11],
 8: [0, 1, 2, 7, 9],
 9: [2, 3, 7, 8, 10],
 10: [3, 4, 7, 9, 11],
 11: [0, 4, 5, 7, 10]})

So I wrote a simple script, but I'm not sure if there's a built-in function that accomplishes the same thing.

def get_adjacency_dict(graph):
    return {vertex: list(graph.neighbors(vertex)) for vertex in graph.vertices()}
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2024-07-23 21:15:16 +0100

updated 2024-07-23 21:16:51 +0100

If G is your graph, then G.to_dictionary() does what you're asking for, I believe.

sage: d = {0: [1, 5, 7, 8, 11],
....:  1: [0, 2, 5, 6, 8],
....:  2: [1, 3, 6, 8, 9],
....:  3: [2, 4, 6, 9, 10],
....:  4: [3, 5, 6, 10, 11],
....:  5: [0, 1, 4, 6, 11],
....:  6: [1, 2, 3, 4, 5],
....:  7: [0, 8, 9, 10, 11],
....:  8: [0, 1, 2, 7, 9],
....:  9: [2, 3, 7, 8, 10],
....:  10: [3, 4, 7, 9, 11],
....:  11: [0, 4, 5, 7, 10]}
sage: G = Graph(d)
sage: G.to_dictionary()
{0: [1, 5, 7, 8, 11],
 1: [0, 2, 5, 6, 8],
 2: [1, 3, 6, 8, 9],
 3: [2, 4, 6, 9, 10],
 4: [3, 5, 6, 10, 11],
 5: [0, 1, 4, 6, 11],
 6: [1, 2, 3, 4, 5],
 7: [0, 8, 9, 10, 11],
 8: [0, 1, 2, 7, 9],
 9: [2, 3, 7, 8, 10],
 10: [3, 4, 7, 9, 11],
 11: [0, 4, 5, 7, 10]}
sage: G.to_dictionary() == d
True
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

Stats

Asked: 2024-07-23 15:30:22 +0100

Seen: 209 times

Last updated: Jul 23