使用递归在词典顺序中生成排列

时间:2016-03-10 04:16:54

标签: python algorithm recursion

我正在执行项目euler q24,但是生成排列的这段代码并没有按预期工作。我不确定如何解释代码的逻辑,但是它使用递归在某个索引处创建每组排列然后移动到下一个索引。

def genPermutation(num,index):
    if (index == (len(num)-1)):
        print(num)
    else:
        i = 0
        while i<(len(num)-index):
            newList = num
            temp = newList[index+i]
            newList.pop(index+i)
            newList.insert(index,temp)
            genPermutation(newList,index+1)
            i = i+1

a = [0,1,2,3,4,5]
genPermutation(a,0)

1 个答案:

答案 0 :(得分:0)

您的主要缺陷是分配列表不会创建新列表,当您递归时,您正在更改调用堆栈中的相同列表,因此您将获得重复和奇怪的排序。
你需要:

newList = num[:]   # Create a new list

然而,你也有一些不必要的东西。 A)你不需要while循环,B)你不需要索引和pop:

def genPermutation(num,index):
    if index == len(num)-1:
        print(num)
        return

    for i in range(index, len(num)):
        newList = num[:]
        temp = newList.pop(i)
        newList.insert(index, temp)
        genPermutation(newList, index+1)

为您提供没有重复的完整列表:

>>> a = list(range(6))
>>> genPermutation(a,0))
[[0, 1, 2, 3, 4, 5],
 [0, 1, 2, 3, 5, 4],
 [0, 1, 2, 4, 3, 5],
 [0, 1, 2, 4, 5, 3],
 [0, 1, 2, 5, 3, 4],
 [0, 1, 2, 5, 4, 3],
 [0, 1, 3, 2, 4, 5],
 [0, 1, 3, 2, 5, 4],
 ...

然而,这整个方法效率很低。与迭代方法相比,使用所有这些列表创建的递归非常昂贵,请参阅itertools.permutation()的实现