File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change 1919import functools
2020from math import sqrt
2121from time import time
22+ from collections .abc import Generator
2223
2324
2425def time_func (func , * args , ** kwargs ):
@@ -60,6 +61,22 @@ def fib_iterative(n: int) -> list[int]:
6061 fib .append (fib [- 1 ] + fib [- 2 ])
6162 return fib
6263
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+
6380
6481def fib_recursive (n : int ) -> list [int ]:
6582 """
@@ -196,10 +213,14 @@ def fib_binet(n: int) -> list[int]:
196213 return [round (phi ** i / sqrt_5 ) for i in range (n + 1 )]
197214
198215
216+
217+
199218if __name__ == "__main__" :
200219 num = 30
201220 time_func (fib_iterative , num )
202221 time_func (fib_recursive , num ) # Around 3s runtime
203222 time_func (fib_recursive_cached , num ) # Around 0ms runtime
204223 time_func (fib_memoization , num )
205224 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