File tree 1 file changed +21
-0
lines changed
1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change 19
19
import functools
20
20
from math import sqrt
21
21
from time import time
22
+ from collections .abc import Generator
22
23
23
24
24
25
def time_func (func , * args , ** kwargs ):
@@ -60,6 +61,22 @@ def fib_iterative(n: int) -> list[int]:
60
61
fib .append (fib [- 1 ] + fib [- 2 ])
61
62
return fib
62
63
64
+ def fib_iterative_yield (n : int ) -> Generator [int ]:
65
+ """
66
+ Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield method to save memory
67
+ >>> f = fib_iterative_yield(3)
68
+ >>> next(f)
69
+ 1
70
+ >>> next(f)
71
+ 1
72
+ >>> next(f)
73
+ 2
74
+ """
75
+ a , b = 0 , 1
76
+ for _ in range (n ):
77
+ yield b
78
+ a , b = b , a + b
79
+
63
80
64
81
def fib_recursive (n : int ) -> list [int ]:
65
82
"""
@@ -196,10 +213,14 @@ def fib_binet(n: int) -> list[int]:
196
213
return [round (phi ** i / sqrt_5 ) for i in range (n + 1 )]
197
214
198
215
216
+
217
+
199
218
if __name__ == "__main__" :
200
219
num = 30
201
220
time_func (fib_iterative , num )
202
221
time_func (fib_recursive , num ) # Around 3s runtime
203
222
time_func (fib_recursive_cached , num ) # Around 0ms runtime
204
223
time_func (fib_memoization , num )
205
224
time_func (fib_binet , num )
225
+ time_func (fib_iterative_yield , num )
226
+
You can’t perform that action at this time.
0 commit comments