Search code examples
pythonpermutationyield

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. The function returns nothing. 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")))

Solution

  • Once the string of digits is down to a single character, remaining becomes an empty string. 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):
        for d in digits:
            remaining = digits.replace(d,"")
            if not remaining:
                yield d
                continue
            for p in permutations(remaining):
                yield d+p