繁体   English   中英

使用递归查找Python中列表的所有排列

[英]Using recursion to find all permutations of a list in Python

因此,我知道此主题已涵盖。 但是,我在自己的实现上遇到了麻烦。

    def permutation(word, fixed = [], passed = ""):
        if passed != "":
            fixed.append(passed)

        if len(word) == 1:
            fixed.append(word[0])
            print fixed
        else:
            for i in range(len(word)):
                passed = word[i]
                rem = word[:i] + word[i+1:]
                permutation(rem, fixed, passed)

    permutation(["a","b","c"])
    raw_input()

我试图不具有返回值,而是到达基数,然后打印结果。 尽管执行此操作时会得到以下信息:

    ['a', 'b', 'c']
    ['a', 'b', 'c', 'c', 'b']
    ['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c']
    ['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c', 'c', 'a']
    ['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c', 'c', 'a', 'c', 'a', 'b']
    ['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c', 'c', 'a', 'c', 'a', 'b', 'b', 'a']

这似乎很接近,但是,我可以说fixed正在收集所有输出,而我并不完全理解为什么。

使用递归时,函数的调用中是否局部存在每个变量集? 我的理解是这样,但实际上似乎并非如此。

顺便说一句,这不是功课。

针对任何感兴趣的人的更新代码:

    def permutation(word, fixed = "", passed = ""):
        if passed != "":
            fixed += passed

        if len(word) == 1:
            fixed += word[0]
            print fixed
        else:
            for i in range(len(word)):
                passed = word[i]
                rem = word[:i] + word[i+1:]
                permutation(rem, fixed, passed)

    permutation(["a","b","c"])
    raw_input()

产生输出:abc acb bac bca cab cba

您的函数传递了对fixed列表的引用,因此您的函数可以对其进行突变。 这个问题的公认答案有一个很好的解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM