从1到100排列一个列表,以便对于任何索引i,它映射到不等于i的j

时间:2018-08-01 18:38:53

标签: algorithm permutation

在python中,有什么精巧的方法来排列数字列表,例如对于ALL元素,索引是不一样的?

例如, [1,2,3]-> [3,1,2]好 [1,2,3]-> [1,3,2]不好。因为1映射到相同的1。

有什么简单的代码可以实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

这里是所有迭代器。

#! /usr/bin/env python

def derangements (v):
    n = len(v)
    #print(("entering", v))
    if 0 == n:
        yield []
    elif 1 == n:
        pass # No derangements;
    elif 2 == n:
        # Special case not really needed.
        yield [v[1], v[0]]
    elif 3 == n:
        # Special case not really needed.
        yield [v[1], v[2], v[0]]
        yield [v[2], v[0], v[1]]
    else:
        for i in range(n-1):
            remaining = v[0:i] + v[i+1:n-1]
            # derangements where ith/last are a 2-cycle.
            for w in derangements(remaining):
                before = w[0:i]
                after = w[i:n-1]
                yield before + [v[n-1]] + after + [v[i]]
            # derangements where nth follows ith goes elsewhere
            for w in derangements(v[0:n-1]):
                before = w[0:i]
                after = w[i+1:n-1] if i < n-2 else []
                yield before + [v[n-1]] + after + [w[i]]


for d in derangements(range(5)):
    print(d)