【问题标题】:Generate Permutation in Lexicographic Order using Recursion使用递归按字典顺序生成排列
【发布时间】:2016-03-10 04:16:54
【问题描述】:

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

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)

【问题讨论】:

  • 有什么理由不使用itertools 模块,例如itertools.permutations('012345')
  • 好吧,我这样做是为了练习我的算法技能,所以使用模块违背了这样做的目的
  • 好的,你的意思是这段代码没有按预期工作?
  • 如中,排列不是按顺序排列的。这是输出的一部分gyazo.com/6dd5f7ada082bc7550cef6823b4a356f

标签: python algorithm recursion


【解决方案1】:

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

newList = num[:]   # Create a new list

但是,您也有一些不必要的问题。 A) 你不需要 while 循环,B) 你不需要索引和弹出:

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()

的实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多