こんな感じでしょうか。最後一回無駄な計算はしていますが。
Python
1>>> def func_repeat(I):
2... x = 1
3... for i in range(0, I):
4... yield x
5... x *= 2
6...
7>>> list(func_repeat(11))
8[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
そういえば、そもそもご提示のコードは再帰関数じゃないですね。
再帰を使って書くなら、こんな感じです。
Python
1>>> def recursive_func_repeat(I, ret):
2... if not I:
3... return ret
4... ret.append(2 * ret[-1])
5... return recursive_func_repeat(I-1, ret)
6...
7>>> recursive_func_repeat(10, [1])
8[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
最終的にリストにするなら、ジェネレータとあまり性能差はないかと思います。
(追記:append呼び出しのオーバーヘッドに留意する必要はあります。)
再帰が深くなりすぎるとスタックから溢れますが...
Python
1>>> recursive_func_repeat(10000, [1])
2Traceback (most recent call last):
3 File "<stdin>", line 1, in <module>
4 File "<stdin>", line 5, in recursive_func_repeat
5 File "<stdin>", line 5, in recursive_func_repeat
6 File "<stdin>", line 5, in recursive_func_repeat
7 [Previous line repeated 995 more times]
8RecursionError: maximum recursion depth exceeded
可読性に大きな差がないのであれば、再帰を積極的に採用する理由はないです。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/25 11:01
2017/11/25 11:08
2017/11/25 11:13
2017/11/25 11:46