python - 使用递归查找数组的排列

标签 python

我想出了以下功能:

def permutations(elements, arr, index):
    if len(elements) == index:
        print arr
    for i in xrange(index, len(elements)):
        arr[index] = elements[i]
        permutations(elements, arr, index+1)

permutations([1,2,3], [0,0,0], 0)

但是,它正在打印:

[1, 2, 3]
[1, 3, 3]
[2, 2, 3]
[2, 3, 3]
[3, 2, 3]
[3, 3, 3]

我的递归有什么问题?

最佳答案

好吧,我发现这是一个 Java 字符串递归排列算法,我将其翻译成 Python。我认为这是最好的解决方案:

def permutation(aux, ls):
    if len(ls) == 0: 
        print(aux)
    else:
        for i in range(len(ls)):
            permutation(aux + [ls[i]], ls[0:i] + ls[i+1:len(ls)])

permutation([], [1, 2, 3])

这是输出:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

关于python - 使用递归查找数组的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935755/

相关文章:

python - Pycassa,线程池, "Exception in thread Thread-3 (most likely raised during interpreter shutdown):"

python - 如何让代码暂停直到用户点击回车键?

python - tensorflow 自动编码器 : Current implementation does not yet support strides in the batch and depth dimensions

python - 如何将项目附加到另一个文件中的列表并使用更新的列表保存该文件

python - 如何使用 Python 根据日期和术语从 Pubmed 检索信息?

python:如何融化保留特定顺序/自定义排序的数据框

python - 使用基类成员来跟踪派生类实例

python - 根据列之间的条件删除数据框的值

Python Azure 函数处理 blob 存储

python - 从 bucket.objects.all() 迭代中解压 s3.ObjectSummary