繁体   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