Search code examples
pythontuplescycle

Using Python to find the length of a cycle in array of tuples


I have an array of tuples; say,

[(1,2), (2,1), (3,4), (4,5), (5,3)]

There are two cycles in the above; one of length 2 and one of length 3. Is there a built-in function (or package) in Python that allows me to return a list of all cycle lengths? For the above example, it should return [2, 3].


Solution

  • You can use the third-party library networkx:

    import networkx as nx
    
    edges = [(1, 2), (2, 1), (3, 4), (4, 5), (5, 3)]
    G = nx.DiGraph(edges)
    
    [len(cycle) for cycle in list(nx.simple_cycles(G))] # [3, 2]