1

我有一个数组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]

现在我想形成新的数组a11a22如下所示; 在此处输入图像描述

我有一种方法可以在给定的排列中给出所有循环,但是从中构造新数组似乎很复杂。在 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)
4

1 回答 1

1

您可以itertools.permutations获取 的 项的不同排列a,然后使用itertools.cycle循环遍历将 的 子列表的项映射a到其索引的字典,并使用映射压缩 的 子列表c以生成遵循循环字典指定的索引的序列:

a = [[1,2,3,4,5,6,7,8,9,10],[4,1,6,2,3,5,8,9,7,10]]
c = [[4, 2, 1], [6, 5, 3], [8, 9, 7], [10]]
from itertools import cycle, permutations
print([[d[i] for i in range(len(d))] for l in permutations(a) for d in ({p[n]: n for s, p in zip(c, cycle({n: i for i, n in enumerate(s)} for s in l)) for n in s},)])

这输出:

[[1, 2, 6, 4, 3, 5, 7, 8, 9, 10], [4, 1, 3, 2, 5, 6, 8, 9, 7, 10]]
于 2018-10-21T12:58:47.397 回答