【发布时间】: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