Generator question
Mathias Panzenboeck
e0427417 at student.tuwien.ac.at
Sun Nov 26 18:25:52 EST 2006
Robert Kern wrote:
> Timothy Wu wrote:
>> Hi,
>>
>> Using generator recursively is not doing what I expect:
>>
>> def test_gen(x):
>> yield x
>> x = x - 1
>> if x != 0:
>> test_gen(x)
>
> The only thing that the last line does is *create* a new generator object. You
> need to actually iterate over it and yield its values. E.g.
>
>
> In [2]: def test_gen(x):
> ...: yield x
> ...: x -= 1
> ...: if x != 0:
> ...: for y in test_gen(x):
> ...: yield y
> ...:
> ...:
>
> In [3]: list(test_gen(3))
> Out[3]: [3, 2, 1]
>
>
why not this?
def test_gen(x):
for y in xrange(x,0,-1):
yield y
or even better/shorter:
test_gen = lambda x: xrange(x,0,-1)
More information about the Python-list
mailing list