help with generators
Steven Bethard
steven.bethard at gmail.com
Thu May 19 10:09:29 EDT 2005
George Sakkis wrote:
> "Steven Bethard" wrote:
>
>>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)
>>...
[snip]
> A caveat of the implementation above: it yields the same instance (s),
> which is unsafe if the loop variable is modified (e.g. in the "for s in
> bin(n)" loop, s should not be modified). Moreover, each yielded value
> should be 'consumed' and then discarded; attempting to store it (as in
> list(bin(n))) references only the last yielded value.
Yup. However, this was the most direct translation of the OP's original
function (which also only had a single list). Since the question was
about how generators worked, I figured the most direct translation would
probably be the most useful response.
> Here's a shorter, clear and safe implementation:
>
> def bin2(n):
> if n:
> for tail in bin2(n-1):
> yield [0] + tail
> yield [1] + tail
> else:
> yield []
This is definitely the way I would have written it.
STeVe
More information about the Python-list
mailing list