def identify_cycles(l1, l2):
d1 = {val: idx for idx, val in enumerate(l1)}
# This assumes unique values in input l1, but I think the question does too
out = []
for idx, val in enumerate(l1):
curr = l2[idx]
if curr == val or any(val in s for s in out):
continue # If this value doesn't move, or we've seen this cycle, then skip
x = set([val]) # Otherwise, we're at the start of a new cycle
while curr != val:
x.add(curr) # The value at this index in l2 is also in this cycle
curr = l2[d1[curr]]
# The next value in the cycle will be in l2 at the index that curr is at in l1
out.append(x)
return out
print(identify_cycles(lista, output))
# [{8, 6, 7}, {9, 10, 11}, {12, 13, 14}, {16, 17, 15}, {18, 19, 20}]
I believe the above should be able to identify cycles of any length > 1.
0
solved Provide the python code: Identify when the elements of a list exchanged positions in groups of three [closed]