我有一个数组a = [[1,2,3,4,5,6,7,8,9,10],[4,1,6,2,3,5,8,9,7,10]], where lets say a1 = [1,2,3,4,5,6,7,8,9,10] and a2 = [4,1,6,2,3,5,8,9,7,10]
,我从中构造了循环置换。注意 a1 是一个排序数组。例如,在我的情况下,周期是;
c = [[4, 2, 1], [6, 5, 3], [8, 9, 7], [10]]
lets say c1 = [4, 2, 1]
c2 = [6, 5, 3]
c3 = [8, 9, 7]
c4 = [10]
我有一种方法可以在给定的排列中给出所有循环,但是从中构造新数组似乎很复杂。在 python3 中实现这一点的任何想法将不胜感激。
------------------
获得周期;
import numpy as np
import random
def cx(individual):
c = {i+1: individual[i] for i in range(len(individual))}
cycles = []
while c:
elem0 = next(iter(c)) # arbitrary starting element
this_elem = c[elem0]
next_item = c[this_elem]
cycle = []
while True:
cycle.append(this_elem)
del c[this_elem]
this_elem = next_item
if next_item in c:
next_item = c[next_item]
else:
break
cycles.append(cycle)
return cycles
aa = cx([4,1,6,2,3,5, 8,9,7,10])
print("array: ", aa)