4
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 has been bugging me, since I don't understand how the yields connect to each other. My understanding was that yield acts like a return, but it stops temporarily until it is called again. How do these yields work?

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Justin Baik
  • 61
  • 1
  • 6

1 Answers1

1

It might help seeing a version that doesn't 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" of "return" with "yield". In the "return" version we needs to accumulate the result while in the "yield" version all that needs to be done is to "yield" the current permutation.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129