-2

I'm new to Python, and have spent a while without programming so would very much appreciate your help.

I have to look for all n-length cycles in a given data-structure -I'm currently using lists but maybe a dict would do the work-

Each element in the first row maps directly to the element below it and a cycle is formed if repeated use of the mapping leads back to the initial value. Let's say I have:

A=[[2,3,4,5,6,7,8,9,10],
   [6,3,6,1,8,8,4,1,9]]

then cycles are (3) and (4,6,8)

or

A=[[2,  3, 4, 5, 6,  7,  8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
   [17, 7, 7, 3, 12, 18, 1, 8, 20, 1,  6,  13, 4,  17, 4,  13, 5,  10]]

Where cycles are (3,7,18,5), (6,12) and (13)

I'm really stuck so thanks in advance for your help.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jtppeamc
  • 7
  • 2
  • 1
    show us what you've tried. This looks like a home work question – taesu Apr 08 '15 at 15:12
  • 2
    It's not clear what the data format is. Are you looking for *Tarjan's strong connected components analysis?* – Willem Van Onsem Apr 08 '15 at 15:13
  • The problem seems rather straightforward: for each number in the first row, check what is at its position in the second row. Then find that number in the first row and repeat. Stop if you visit a number you've visited before. If that number is the first one, report a cycle, otherwise don't. You should be able to show where you got stuck. – IVlad Apr 08 '15 at 15:17
  • I don't see that. Applying that logic to the first cycle `3` doesn't work. The cycle probably is that in the second row of `A`, at position `3`, the number is `1`, which is the *index* that the `3` had in the first row. I can't see the cycle for `(4,6,8)` though. – emvee Apr 08 '15 at 15:21
  • 1
    @haavee - go from `4` on the first row to the `6` on the second (which is below it), then from the `6` on the first row to the `8` on the second row (again, below it). Finally, from the `8` on the first row to the `4` below it, and that's the cycle. – IVlad Apr 08 '15 at 15:27
  • Ah thx! Now I see. In that case, I don't think it matters very much wether you use a list or a dict. – emvee Apr 08 '15 at 15:30

1 Answers1

0

Thanks guys! It was so simple I just couldn't see it... Arranging elements from A into 2 columns (in pairs A[0][i],A[1][i]) and feeding it to a networkx object like

>>>G = nx.DiGraph(A)
>>>list(nx.simple_cycles(G))
>>>[[12, 6], [5, 3, 7, 18], [13]]

Produces the output.

jtppeamc
  • 7
  • 2