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.Tue, 23 Jul 2024 21:15:16 +0200- Does Sage have a built-in function to output an adjacency list?https://ask.sagemath.org/question/78410/does-sage-have-a-built-in-function-to-output-an-adjacency-list/ 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()}
Tue, 23 Jul 2024 15:30:22 +0200https://ask.sagemath.org/question/78410/does-sage-have-a-built-in-function-to-output-an-adjacency-list/
- Answer by John Palmieri for <p>We know that SageMath supports adjacency list input, but I haven't seen an output function.</p>
<pre><code>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]})
</code></pre>
<p>So I wrote a simple script, but I'm not sure if there's a built-in function that accomplishes the same thing.</p>
<pre><code>def get_adjacency_dict(graph):
return {vertex: list(graph.neighbors(vertex)) for vertex in graph.vertices()}
</code></pre>
https://ask.sagemath.org/question/78410/does-sage-have-a-built-in-function-to-output-an-adjacency-list/?answer=78414#post-id-78414If `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
TrueTue, 23 Jul 2024 21:15:16 +0200https://ask.sagemath.org/question/78410/does-sage-have-a-built-in-function-to-output-an-adjacency-list/?answer=78414#post-id-78414