简体   繁体   English

递归置换字符串崩溃

[英]recursion permutation string crash

I'm writing a code "recursion permutation of string" in Python It crashed after one tree(?) cycle. 我正在Python中编写代码“字符串的递归置换”。它在一个树(?)循环后崩溃。 I can not find the reason why. 我找不到原因。 please explain about it. 请对此进行解释。

memory = []
memory2 = []

def permutation(s):


if len(s)==1:
    return s


for i,char in enumerate(s):
     returns= permutation(s[:i] + s[i+1:])
     print(returns)
     if returns == None:
         for j in memory:
            memory2.append(s[i] + j)
         memory = []
     memory.append(s[i] + returns)
     print(memory)
 s = "ABC"
 print(permutation(s))

After it formed the memory[cb, bc] It should goes to the next for loop. 形成memory [cb,bc]之后,它应该转到下一个for循环。 but it just end it. 但这只是结束了。

I think you have forget 'else' in your condition: 我认为您已经忘记了其他情况:

memory = []
memory2 = []

def permutation(s):
    global memory
    global memory2

    if len(s)==1:
        return s

    for i, char in enumerate(s):
        returns = permutation(s[:i] + s[i+1:])

        if returns == None:
            for j in memory:
                memory2.append(s[i] + j)
            memory = []
        else: # <--- here 
            memory.append(s[i] + returns)

s = "ABC"
permutation(s)
print(memory2)

You can correct your function like so: 您可以像这样纠正您的功能:

def permutations(s):
    if len(s) <= 1:
        return [s]
    result = []
    for i, letter in enumerate(s):
        for perm in permutations(s[:i] + s[i + 1:]):
            result.append(letter + perm)
    return result

or use standard library function itertools.permutations : 或使用标准库函数itertools.permutations

from itertools import permutations
perms = ["".join(perm) for perm in permutations(s)]

both of them return the same result: 他们两个返回相同的结果:

s = "abc"
print(permutations(s))  # ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

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

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