Ask Your Question

Revision history [back]

You can also use method all_simple_paths, and there si no need for removing v from the graph sage def FindCycle(G, v, cycle_len): for cycle in G.all_simple_paths(starting_vertices=[v], ending_vertices=[v], max_length=cycle_len): if len(cycle) == cycle_len + 1: return cycle return None For instance sage sage: FindCycle(graphs.CompleteGraph(4), 0, 3) [0, 1, 2, 0] It remains to deal with the special cases cycle_len == 1 which can happen if the graph has loops and the case cycle_len == 2 for which the proposed method returns a non simple cycle (e.g., [0, 1, 0]),

click to hide/show revision 2
No.2 Revision

You can also use method all_simple_paths, and there si no need for removing v from the graph graph

sage
def FindCycle(G, v, cycle_len):
    for cycle in G.all_simple_paths(starting_vertices=[v], ending_vertices=[v], max_length=cycle_len):
        if len(cycle) == cycle_len + 1:
            return cycle
    return None

For instance instance

sage
sage: FindCycle(graphs.CompleteGraph(4), 0, 3)
[0, 1, 2, 0]

It remains to deal with the special cases cycle_len == 1 which can happen if the graph has loops and the case cycle_len == 2 for which the proposed method returns a non simple cycle (e.g., [0, 1, 0]),