Recursion and Generators

Paramjit Oberoi p_s_oberoi at hotmail.com
Sat Jul 10 19:38:16 CEST 2004


> def testRecursion(n):
>     if n == 1:
>         yield [1]
>     else:
>         for result in testRecursion(n-1):
>             yield result + [n]
> 
> print list(testRecursion(4))

Is this what you were trying to do?

>>> def testRecursion(n):
...     if n==1:
...         yield 1
...     else:
...         for x in testRecursion(n-1): yield x
...         yield n
...
>>> list(testRecursion(1))
[1]
>>> list(testRecursion(2))
[1, 2]
>>> list(testRecursion(3))
[1, 2, 3]
>>> list(testRecursion(4))
[1, 2, 3, 4]

The generator should yield individual values one after
another, unlike a list of all values like in your example.

HTH,
-param



More information about the Python-list mailing list