簡體   English   中英

有沒有一種方法可以在不使用循環和列表理解的情況下在 python 中獲取字符串的排列 - 只是遞歸

[英]Is there a way of getting the permutations of a string without using loops and list comprehension in python - Just recursion

有沒有辦法在不使用循環和列表理解的情況下完成上述操作 - 只是遞歸?

這是我的 for 循環解決方案:

def permutations(s):        
    if(len(s)==1):
        return [s]
    combs = []
    for i in range(len(s)):
        for perm in permutations(s[:i]+s[i+1:]):
            combs += [s[i]+perm]
    return combs

例子:

輸入:“bca”

output:[“abc”,“acb”,“bca”,“bac”,“cab”,“cba”]

基本上,您將循環的結束條件移動到遞歸中的結束條件。 您還可以將中間結果沿鏈傳遞,以避免 for 循環將數據附加到結果中。

def permutations(s, i=0, curr=""):
    # end what was the for loop
    if i == len(s):
        return []
    if len(s) == 1:
        return [curr + s]
    return [
        *permutations(s[:i] + s[i+1:], 0, curr + s[i]),
        *permutations(s, i+1, curr),
    ]

無需重新發明輪轂:

from itertools import permutations

combs = [ ''.join(p) for p in permutations(s) ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM