簡體   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