title: How to determine cycles in a list?
body: <p>Consider a list of integer indices, <code>indices</code>. All elements of <code>indices</code> are within the bounds of the list <code>indices</code>. All the values in the list <code>indices</code> are unique. Example <code>[2, 0, 1, 4, 3, 5]</code>.</p>
  
  <p>Given an index, (e.g <code>0</code>), move on to <code>indices[0]</code> (i.e <code>2</code> in the example above). Repeating that can be done indefinitely. A cycle occurs when a move returns to an already visited index. There is always at least one cycle. The sum of the lengths of the cycles is equal to the length of the list <code>indices</code>. </p>
  
  <p>I need to create a function <code>cycles(indices)</code> that returns a list of all cycles in <code>indices</code>.</p>
  
  <p>For the example above, the expected output list is <code>[[2, 0, 1], [4, 3], [5]]</code>.</p>
  
  <p>For the list <code>[0, 1, 2, 3]</code>, the cycles are trivial and of the form <code>[[0], [1], [2], [3]]</code>.</p>
  
  <p><strong>Note</strong>: The order of the output cycles and the order of the indices do not matter. For example: <code>[[2, 0, 1], [4, 3], [5]]</code> is equivalent to <code>[[3, 4], [0, 1, 2], [5]]</code></p>
  
  <p>This is the code I have come up with thus far:</p>
  
  <pre><code>def cycles(indices):
      cycles = []
      old_i = []
      i = 0
      while i in range(len(indices)):
          old_i.append(i)
          i = indices[i]
          if i in old_i:
              cycles.append(old_i)
              i = max(old_i) + 1
              old_i = []
  
      return cycles
  </code></pre>
  
  <p>The problem with my code is that it does not recheck if there is a smaller cycle within the elements of a bigger cycle, if it has already passed the elements of the smaller cycle. Any suggestions as to how to solve this coding problem?</p>
  
  <p>Please note, I am just beginning to learn how to program and I am taking an introductory online course, so I would appreciate simple solutions.</p>