1

I have problems understanding how this generator works. How exactly does it create permutations? Also, in the code, what does yield[items[i]] + cc yield and to where? What is added to the list yield[] each time yield[items[i]] + cc is called? (is anything even added?) i'm sorry but I'm really confused:(

sorry for such a novice question and I hope someone could help me understand this better! Thanks!

def permutations(items):

    n = len
    if n == 0:
        yield[]
    else:
        for i in range(len(items)):
           for cc in permutations(items[:i] + items[i+1:]:
               yield[items[i]] + cc
for p in permutations(['r','e','d']):
    print ''.join(p)
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
user3441773
  • 9
  • 1
  • 3
  • 1
    http://www.dabeaz.com/generators/Generators.pdf was useful to me when I first started learning. – bbayles Mar 20 '14 at 11:51
  • 1
    There are some errors in this snippet. `n` should be `len(items)` and there's a closing parenthesis missing in the second `for` loop – svvac Mar 20 '14 at 11:54
  • Also, [this SO question](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained) explains a lots about generators ;-) – svvac Mar 20 '14 at 11:55
  • Your function is a recursive power set algorithm. There is a pretty good description [here](http://www.ecst.csuchico.edu/~amk/foo/csci356/notes/ch1/solutions/recursionSol.html). – wwii Mar 20 '14 at 12:04

1 Answers1

0

yield is a statement, like print or return.

imagine that you have a function:

def blah(x):
    return x
    return x + 1
    return x + 2
    return x + 3

and then you call it:

print blah(10)

it will only return 10, and it will never get to 11, 12, or 13, as the function is finished.

when you use yield, you are essentially saying, "pretend this function is a list..." and then the yield statement is used from the function to return one value after another, until it's run out, instead of returning just one value.

so:

def gen_blah(x):
    yield x
    yield x+1
    yield x+2
    yield x+3

for i in gen_blah(10):
    print i

will print 10 then 11, 12 and 13.

So the permutations function is yielding each of the values one at a time, which then the for loop outside of the generator function is using.

Daniel
  • 1,410
  • 12
  • 17