简体   繁体   English

在 Python 3 中生成排列

[英]Generating permutations in Python 3

I wrote this simple permutations generator in Python 3. The permuted digits are a string, and the function should yield successive strings as well.我在 Python 3 中编写了这个简单的排列生成器。排列后的数字是一个字符串,function 也应该产生连续的字符串。 The function returns nothing. function 什么也不返回。 Could I please ask for some help with this?我可以请我帮忙吗?

def permutations(digits):
    if digits:
        for d in digits:
            remaining = digits.replace(d,"")
            for p in permutations(remaining):
                yield d+p


print(list(permutations("12345")))

Once the string of digits is down to a single character, remaining becomes an empty string.一旦数字字符串减少到一个字符, remaining的就变成一个空字符串。 Then the next recursion doesn't yield anything.然后下一次递归不会产生任何东西。 That means the next higher recursion level never executes its loop and so on and so forth.这意味着下一个更高的递归级别永远不会执行它的循环等等。

The simplest fix would be this:最简单的解决方法是:

def permutations(digits):
    if not digits:
        yield ""
        return
    for d in digits:
        remaining = digits.replace(d,"")
        for p in permutations(remaining):
            yield d+p

Consider the base case of your function, where there is a single character.考虑 function 的基本情况,其中只有一个字符。 The permutations of 'a' are ['a'] . 'a'的排列是['a'] Your code, however, returns an empty list because it never enters the inner for loop (it returns nothing if the length of the string is zero).但是,您的代码返回一个空列表,因为它从不进入内部 for 循环(如果字符串的长度为零,则它不返回任何内容)。

You can fix this by adding an if statement to explicitly handle the case where there is one character in the string.您可以通过添加 if 语句来显式处理字符串中有一个字符的情况来解决此问题。

def permutations(digits):
    if len(digits) == 0:
        return
    elif len(digits) == 1:
        yield digits
    else:
        for d in digits:
            remaining = digits.replace(d,"")
            for p in permutations(remaining):
                yield d+p


print(list(permutations("12345")))

The problem is subtle.问题很微妙。 The inner-most recursion does not yield anything, not even an empty string.最里面的递归不会产生任何东西,甚至不会产生空字符串。 Therefore its caller does not loop over any subpermutations.因此,它的调用者不会遍历任何子排列。 etc.等等

def permutations(digits):
    if digits:
        for d in digits:
            remaining = digits.replace(d,"")
            for p in permutations(remaining):
                yield d+p
    else:
        yield ""

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

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