范围内元组的排列

时间:2015-01-10 19:38:17

标签: python algorithm permutation

当我致电permutations(range(0,nCols))时,它会给我一个这样的排列:

(0, 1, 2) (0, 2, 1) (1, 0, 2) (1, 2, 0) (2, 0, 1) (2, 1, 0)

但除了上面的排列之外我想要的是包含少于nCols个项目的元组,所以像这样:

(0) (1) (2) (0, 1) (0, 2) (1, 2)

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

2 个答案:

答案 0 :(得分:2)

由于你发布了下面的模块itertools.permutations中的代码,你应该马上看到它。 " r"

中的论点
def permutations(iterable, r=None):

是排列应该具有的长度。你可以循环遍历从1到n的范围(可迭代的长度),如下所示:

from itertools import permutations
for i in range(1,nCols+1):
    print(list(permutations(range(nCols),i))

这假设你真的意味着排列。在您的示例中,2长度排列未完成。

答案 1 :(得分:1)

这段代码似乎是itertools.permutations的副本,所以我会在这里使用:

from itertools import permutations

all_permutations = []

for index in range(1, nCols+1):
   all_permutations += permutations(range(nCols), index)

print(all_permutations)

请注意,第二个参数r指定要生成的排列的长度。因此,我们可以遍历并生成每个长度的所有排列,直到nCols。和繁荣!