help with generators

Steven Bethard steven.bethard at gmail.com
Thu May 19 01:06:24 EDT 2005


Mayer wrote:
> Hello:
> 
> I need some help in understanding generators. I get them to work in
> simple cases, but the following example puzzles me. Consider the
> non-generator, "ordinary" procedure:
> 
> def foo(n):
>     s = []
>     def foo(n):
>         if n == 0:
>             print s
>         else:
>             s.append(0)
>             foo(n - 1)
>             s.pop()
>             s.append(1)
>             foo(n - 1)
>             s.pop()
>     foo(n)
> 
> foo(n) prints all n-bit-wide binary numbers as a list. I would now like
> to create a generator for such numbers:
> 
> def bin(n):
>     s = []
>     def bin(n):
>         if n == 0:
>             yield s
>         else:
>             s.append(0)
>             bin(n - 1)
>             s.pop()
>             s.append(1)
>             bin(n - 1)
>             s.pop()
>     return bin(n)
> 
> yet this doesn't work as expected. Can someone please explain why?

It would help if you explained what you expected.  But here's code that 
prints about the same as your non-generator function.

py> def bin(n):
...     s = []
...     def bin(n):
...         if n == 0:
...             yield s
...         else:
...             s.append(0)
...             for s1 in bin(n - 1):
...                 yield s1
...             s.pop()
...             s.append(1)
...             for s1 in bin(n - 1):
...                 yield s1
...             s.pop()
...     return bin(n)
...
py> for s in bin(1):
...     print s
...
[0]
[1]
py> for s in bin(2):
...     print s
...
[0, 0]
[0, 1]
[1, 0]
[1, 1]

Note that to make the recursive calls work, you *must* iterate through 
them, thus what was in your code:

     bin(n - 1)

now looks like:

     for s1 in bin(n - 1):
         yield s1

This is crucial.  bin(n - 1) creates a generator object.  But unless you 
put it in a for-loop (or call it's .next()) method, the generator will 
never execute any code.

HTH,

STeVe



More information about the Python-list mailing list