# How to generate a chain of permutations?

Good evening. How can I find out which chain rearrangements can exist within a permutation if the permutation and the original sequence(both in list view)?
Let me explain: a chain of permutation is a sequence a(n) for which is fulfilled:
A'[a(n+1)] = B'[a(n)], where A' is a sequence consisting of N first natural numbers, starting from zero (0,1,2,3...,N), B' - a permutation of elements of this sequence. The number of members in the chain of permutations of course. Each member of the chain permutation is a member of the sequence A'.
Example:
Original sequence: A' [0,1,2,3,4,5,6]
Permutation: B' [ 2,6,0,5,1,3,4]
Chain: [1,4,6,1]
[0,2,0]

Ideas are: take A'[0], looking for the index of the element with the same value in B'. This index - 2. Next, look for the index of two in A'. Is 0. The circuit was closed, turned out 0 2 0
Throw from the original sequence all the elements of the circuit. Have:
A' = [1,3,4,5,6]
A'[0] =1
Searching In' unity. We have it at number 4. Then look for the index In four' is 6. Then look for the index of six in B', it turns out 1. But 1 is already in the circuit changes, therefore, the circuit is closed. Have a chain 1 4 6 1
April 3rd 20 at 17:23
April 3rd 20 at 17:25
Solution
``````A = [0,1,2,3,4,5,6]
B = [2,6,0,5,1,3,4]

def chains(a,b):
chain, list_chains = [a[0]], []
while a:
chain += [b.index(chain[-1])]
if chain[0] == chain[-1]:
list_chains += [chain]
a = [i for i in a if i not in chain]
if a:
chain = [a[0]]
return list_chains

print(chains(A,B))

In [3]:
[[0, 2, 0], [1, 4, 6, 1], [3, 5, 3]]``````

Find more questions by tags Python