提供python代码:确定列表元素何时以三个为一组交换位置

时间:2018-01-20 19:46:24

标签: python list vertices

Syppose我有一个表示图形顶点的列表。

 lista = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

我拿到列表,然后计算顶点的自同构组。这将返回一个新列表,其中我的顶点以三个为一组进行交换。输出列表如下:

 output = [0,1,2,3,4,5,7,8,6,10,11,9,13,14,12,16,17,15,19,20,18]

如果您手动分析列表,您可以识别以三个为一组交换的元素。在我们的示例中,

changed_elements = [[7,8,6],[10,11,9],[13,14,12],[16,17,15],[19,20,18]]

我想要如何识别和组合一起交换的三个元素的python代码或伪代码

1 个答案:

答案 0 :(得分:0)

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}]

我相信以上应该能够识别任何长度的周期> 1.