简体   繁体   中英

Can a python generator use recursion?

>>> def gen(num):
...     print "inside \n"
...     if num < 10:
...         gen(num +1)
...     yield num
... 
>>> x = gen(1)
>>> for i in x:
...     print i
... 
inside

1
>>> 

Why is inside printed only once? I thought it would get printed many more times.

You only created the recursive generator, you never iterated over it . If you don't ask a generator for values, it'll never execute.

Add a loop and yield the results of the recursive call:

def gen(num):
    print "inside"
    if num < 10:
        for recursive_result in gen(num + 1):
            yield recursive_result
    yield num

This produces:

>>> def gen(num):
...     print "inside"
...     if num < 10:
...         for recursive_result in gen(num + 1):
...             yield recursive_result
...     yield num
... 
>>> x = gen(1)
>>> for i in x:
...     print i
... 
inside 
inside 
inside 
inside 
inside 
inside 
inside 
inside 
inside 
inside 
10
9
8
7
6
5
4
3
2
1

You are evidently using Python 2, but if you were to use Python 3.3 you can make use of generator delegation and instead of looping use yield from :

def gen(num):
    print("inside")
    if num < 10:
        yield from gen(num + 1)
    yield num

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM