How to stop sage graph generating iterator after N iterations?
Question:
I want to create N planar graphs using sagemath’s graph.planar_graphs iterator. The problem is that this function return all possible planar graphs given a certain number of vertices. What I want to do is something like:
while len(gen) < N:
gen = list(graphs.planar_graphs(50))
So in the end, I want a list with the first N generated planar graphs instead of all of them (since thats many orders of magnitudes more graphs and computationally very expensive).
Answers:
One nice thing about iterators is you can grab
as many or as few elements as you want.
Iterator for all planar graphs of order 50:
sage: planar_50 = graphs.planar_graphs(50)
Grab the first four:
sage: planar_50_4 = [next(planar_50) for _ in range(4)]
Check:
sage: planar_50_4
[Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices]
Turn that into a function:
def planar_graphs_order_k_first_n(k, n):
pg = graphs.planar_graphs(k)
return [next(pg) for _ in range(n)]
Use it:
sage: planar_graphs_order_k_first_n(50, 4)
[Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices]
I want to create N planar graphs using sagemath’s graph.planar_graphs iterator. The problem is that this function return all possible planar graphs given a certain number of vertices. What I want to do is something like:
while len(gen) < N:
gen = list(graphs.planar_graphs(50))
So in the end, I want a list with the first N generated planar graphs instead of all of them (since thats many orders of magnitudes more graphs and computationally very expensive).
One nice thing about iterators is you can grab
as many or as few elements as you want.
Iterator for all planar graphs of order 50:
sage: planar_50 = graphs.planar_graphs(50)
Grab the first four:
sage: planar_50_4 = [next(planar_50) for _ in range(4)]
Check:
sage: planar_50_4
[Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices]
Turn that into a function:
def planar_graphs_order_k_first_n(k, n):
pg = graphs.planar_graphs(k)
return [next(pg) for _ in range(n)]
Use it:
sage: planar_graphs_order_k_first_n(50, 4)
[Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices,
Graph on 50 vertices]