Consider a list of integer indices, indices
. All elements of indices
are within the bounds of the list indices
. All the values in the list indices
are unique. Example [2, 0, 1, 4, 3, 5]
.
Given an index, (e.g 0
), move on to indices[0]
(i.e 2
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 indices
.
I need to create a function cycles(indices)
that returns a list of all cycles in indices
.
For the example above, the expected output list is [[2, 0, 1], [4, 3], [5]]
.
For the list [0, 1, 2, 3]
, the cycles are trivial and of the form [[0], [1], [2], [3]]
.
Note: The order of the output cycles and the order of the indices do not matter. For example: [[2, 0, 1], [4, 3], [5]]
is equivalent to [[3, 4], [0, 1, 2], [5]]
This is the code I have come up with thus far:
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
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?
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.