How does “exit” work in this permutation generator?

def perm_generator(lst):
    if len(lst) == 1:
        yield lst
    else:
        for i in range(len(lst)):
            for perm in perm_generator(lst[:i] + lst[i+1:]):
                yield [lst[i]] + perm

This code listened to me since I do not understand how they yieldconnect to each other. I realized that it was yieldacting like return, but temporarily stopped until it was called again. How do these work yield?

+4
source share
1 answer

This may help to see a version that does not use generators:

def perm_generator(lst):
    res = []
    if len(lst) == 1:
        return [lst]
    else:
        for i in range(len(lst)):
            for perm in perm_generator(lst[:i] + lst[i+1:]):
                res.append([lst[i]] + perm)
    return res

gen = perm_generator([1,2,3])
print gen # prints [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

As you can see, this is not a "find and replace" "return" with a "yield". In the "return" version, we need to accumulate the result, and in the "yield" version all we need to do is to "issue" the current permutation.

+1

All Articles