ジェネレータと再帰
- ピラミッドを作る - どう書く?org (http://ja.doukaku.org/8/)
ピラミッドを作る問題を考えていて、ジェネレータと再帰を組み合わせる処理を書いていたら、yieldした関数の中で再帰関数を呼び出せなかった。
>>> def pyramid(n): ... def rec(mark=1, space=n-1): ... if space >= 0: ... yield ' ' * space + '*' * mark ... rec(mark+2, space-1) ... return rec() ... >>> p = pyramid(4) >>> print p.next() * >>> print p.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
ジェネレータと再帰を組み合わせることはできないのだろうか?それともバグだろうか?エラーの原因はyieldが存在しないからだが、再帰が使えない理由がよく分からない…。